File size: 4,072 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
// @flow
const debug = require('debug')('api:graphql');
import { ApolloServer } from 'apollo-server-express';
import responseCachePlugin from 'apollo-server-plugin-response-cache';
import depthLimit from 'graphql-depth-limit';
import costAnalysis from 'graphql-cost-analysis';
import { RedisCache } from 'apollo-server-cache-redis';
import createLoaders from './loaders';
import createErrorFormatter from './utils/create-graphql-error-formatter';
import schema from './schema';
import { statsd } from 'shared/statsd';
import { getUserIdFromReq } from './utils/session-store';
import UserError from './utils/UserError';
import type { DBUser } from 'shared/types';
import { getUserById } from '../shared/db/queries/user';

// NOTE(@mxstbr): Evil hack to make graphql-cost-analysis work with Apollo Server v2
// @see pa-bru/graphql-cost-analysis#12
// @author @arianon
class ProtectedApolloServer extends ApolloServer {
  async createGraphQLServerOptions(
    req: express$Request,
    res: express$Response
  ): Promise<*> {
    const options = await super.createGraphQLServerOptions(req, res);

    return {
      ...options,
      validationRules: [
        ...options.validationRules,
        costAnalysis({
          maximumCost: 750,
          defaultCost: 1,
          variables: req.body.variables,
          createError: (max, actual) => {
            const err = new UserError(
              `GraphQL query exceeds maximum complexity, please remove some nesting or fields and try again. (max: ${max}, actual: ${actual})`
            );
            return err;
          },
        }),
      ],
    };
  }
}

let connections = 0;

setInterval(() => {
  statsd.gauge('websocket.connections.count', connections);
}, 5000);

const server = new ProtectedApolloServer({
  schema,
  formatError: createErrorFormatter(),
  // For subscriptions, this gets passed "connection", for everything else "req" and "res"
  context: ({ req, res, connection, ...rest }, ...other) => {
    if (connection) {
      return {
        ...(connection.context || {}),
      };
    }

    // Add GraphQL operation information to the statsd tags
    req.statsdTags = {
      graphqlOperationName: req.body.operationName || 'unknown_operation',
    };
    debug(req.body.operationName || 'unknown_operation');
    const loaders = createLoaders();
    let currentUser = req.user && !req.user.bannedAt ? req.user : null;

    return {
      loaders,
      updateCookieUserData: (data: DBUser) =>
        new Promise((res, rej) =>
          req.login(data, err => (err ? rej(err) : res()))
        ),
      req,
      user: currentUser,
    };
  },
  subscriptions: {
    path: '/websocket',
    onConnect: (connectionParams, rawSocket) => {
      connections++;
      return getUserIdFromReq(rawSocket.upgradeReq)
        .then(id => (id ? getUserById(id) : null))
        .then(user => {
          return {
            user: user || null,
            loaders: createLoaders({ cache: false }),
          };
        })
        .catch(err => {
          console.error(err);
          return {
            loaders: createLoaders({ cache: false }),
          };
        });
    },
  },
  playground: process.env.NODE_ENV !== 'production' && {
    settings: {
      'editor.theme': 'light',
    },
    tabs: [
      {
        endpoint: 'http://localhost:3001/api',
        query: `{
  user(username: "mxstbr") {
    id
    username
  }
}`,
      },
    ],
  },
  introspection: process.env.NODE_ENV !== 'production',
  maxFileSize: 25 * 1024 * 1024, // 25MB
  engine: false,
  tracing: false,
  validationRules: [depthLimit(10)],
  cacheControl: {
    calculateHttpHeaders: false,
    // Cache everything for at least a minute since we only cache public responses
    defaultMaxAge: 60,
  },
  plugins: [
    responseCachePlugin({
      sessionId: ({ context }) => (context.user ? context.user.id : null),
      // Only cache public responses
      shouldReadFromCache: ({ context }) => !context.user,
      shouldWriteToCache: ({ context }) => !context.user,
    }),
  ],
});

export default server;