-
-
Notifications
You must be signed in to change notification settings - Fork 229
Expand file tree
/
Copy pathinstallPostGraphile.ts
More file actions
289 lines (248 loc) · 9.63 KB
/
installPostGraphile.ts
File metadata and controls
289 lines (248 loc) · 9.63 KB
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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
import {
postgraphile,
makePluginHook,
PostGraphileOptions,
Middleware,
enhanceHttpServerWithSubscriptions,
} from "postgraphile";
import { makePgSmartTagsFromFilePlugin } from "postgraphile/plugins";
import { NodePlugin } from "graphile-build";
import { Pool } from "pg";
import { Express, Request, Response } from "express";
import PgPubsub from "@graphile/pg-pubsub";
import PgSimplifyInflectorPlugin from "@graphile-contrib/pg-simplify-inflector";
import GraphilePro from "@graphile/pro"; // Requires license key
import PgTypeEmailPlugin from "../plugins/PgTypeEmailPlugin";
import PgTypeUrlPlugin from "../plugins/PgTypeUrlPlugin";
import PassportLoginPlugin from "../plugins/PassportLoginPlugin";
import PrimaryKeyMutationsOnlyPlugin from "../plugins/PrimaryKeyMutationsOnlyPlugin";
import SubscriptionsPlugin from "../plugins/SubscriptionsPlugin";
import handleErrors from "../utils/handleErrors";
import { getWebsocketMiddlewares, getHttpServer } from "../app";
import { getAuthPgPool, getRootPgPool } from "./installDatabasePools";
import { resolve } from "path";
const TagsFilePlugin = makePgSmartTagsFromFilePlugin(
// We're using JSONC for VSCode compatibility; also using an explicit file
// path keeps the tests happy.
resolve(__dirname, "../../postgraphile.tags.jsonc")
);
type UUID = string;
const isTest = process.env.NODE_ENV === "test";
function uuidOrNull(input: string | number | null): UUID | null {
if (!input) return null;
const str = String(input);
if (
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(
str
)
) {
return str;
} else {
return null;
}
}
const isDev = process.env.NODE_ENV === "development";
//const isTest = process.env.NODE_ENV === "test";
const pluginHook = makePluginHook([
// Add the pub/sub realtime provider
PgPubsub,
// If we have a Graphile Pro license, then enable the plugin
...(process.env.GRAPHILE_LICENSE ? [GraphilePro] : []),
]);
interface IPostGraphileOptionsOptions {
websocketMiddlewares?: Middleware<Request, Response>[];
rootPgPool: Pool;
}
export function getPostGraphileOptions({
websocketMiddlewares,
rootPgPool,
}: IPostGraphileOptionsOptions) {
const options: PostGraphileOptions<Request, Response> = {
// This is for PostGraphile server plugins: https://www.graphile.org/postgraphile/plugins/
pluginHook,
// This is so that PostGraphile installs the watch fixtures, it's also needed to enable live queries
ownerConnectionString: process.env.DATABASE_URL,
// On production we still want to start even if the database isn't available.
// On development, we want to deal nicely with issues in the database.
// For these reasons, we're going to keep retryOnInitFail enabled for both environments.
retryOnInitFail: !isTest,
// Add websocket support to the PostGraphile server; you still need to use a subscriptions plugin such as
// @graphile/pg-pubsub
subscriptions: true,
websocketMiddlewares,
// enableQueryBatching: On the client side, use something like apollo-link-batch-http to make use of this
enableQueryBatching: true,
// dynamicJson: instead of inputting/outputting JSON as strings, input/output raw JSON objects
dynamicJson: true,
// ignoreRBAC=false: honour the permissions in your DB - don't expose what you don't GRANT
ignoreRBAC: false,
// ignoreIndexes=false: honour your DB indexes - only expose things that are fast
ignoreIndexes: false,
// setofFunctionsContainNulls=false: reduces the number of nulls in your schema
setofFunctionsContainNulls: false,
// Enable GraphiQL in development
graphiql: isDev || !!process.env.ENABLE_GRAPHIQL,
// Use a fancier GraphiQL with `prettier` for formatting, and header editing.
enhanceGraphiql: true,
// Allow EXPLAIN in development (you can replace this with a callback function if you want more control)
allowExplain: isDev,
// Disable query logging - we're using morgan
disableQueryLog: true,
// Custom error handling
handleErrors,
/*
* To use the built in PostGraphile error handling, you can use the
* following code instead of `handleErrors` above. Using `handleErrors`
* gives you much more control (and stability) over how errors are
* output to the user.
*/
/*
// See https://www.graphile.org/postgraphile/debugging/
extendedErrors:
isDev || isTest
? [
"errcode",
"severity",
"detail",
"hint",
"positon",
"internalPosition",
"internalQuery",
"where",
"schema",
"table",
"column",
"dataType",
"constraint",
]
: ["errcode"],
showErrorStack: isDev || isTest,
*/
// Automatically update GraphQL schema when database changes
watchPg: isDev,
// Keep data/schema.graphql up to date
sortExport: true,
exportGqlSchemaPath: isDev
? `${__dirname}/../../../../data/schema.graphql`
: undefined,
/*
* Plugins to enhance the GraphQL schema, see:
* https://www.graphile.org/postgraphile/extending/
*/
appendPlugins: [
// Exposes `Email` and `URL` types in the GraphQL schema
PgTypeEmailPlugin,
PgTypeUrlPlugin,
// Adds support for our `postgraphile.tags.json5` file
TagsFilePlugin,
// Simplifies the field names generated by PostGraphile.
PgSimplifyInflectorPlugin,
// Omits by default non-primary-key constraint mutations
PrimaryKeyMutationsOnlyPlugin,
// Adds the `login` mutation to enable users to log in
PassportLoginPlugin,
// Adds realtime features to our GraphQL schema
SubscriptionsPlugin,
],
/*
* Plugins we don't want in our schema
*/
skipPlugins: [
// Disable the 'Node' interface
NodePlugin,
],
graphileBuildOptions: {
/*
* Any properties here are merged into the settings passed to each Graphile
* Engine plugin - useful for configuring how the plugins operate.
*/
},
/*
* Postgres transaction settings for each GraphQL query/mutation to
* indicate to Postgres who is attempting to access the resources. These
* will be referenced by RLS policies/triggers/etc.
*
* Settings set here will be set using the equivalent of `SET LOCAL`, so
* certain things are not allowed. You can override Postgres settings such
* as 'role' and 'search_path' here; but for settings indicating the
* current user, session id, or other privileges to be used by RLS policies
* the setting names must contain at least one and at most two period
* symbols (`.`), and the first segment must not clash with any Postgres or
* extension settings. We find `jwt.claims.*` to be a safe namespace,
* whether or not you're using JWTs.
*/
async pgSettings(req) {
const sessionId = req.user && uuidOrNull(req.user.session_id);
if (sessionId) {
// Update the last_active timestamp (but only do it at most once every 15 seconds to avoid too much churn).
await rootPgPool.query(
"UPDATE app_private.sessions SET last_active = NOW() WHERE uuid = $1 AND last_active < NOW() - INTERVAL '15 seconds'",
[sessionId]
);
}
return {
// Everyone uses the "visitor" role currently
role: process.env.DATABASE_VISITOR,
/*
* Note, though this says "jwt" it's not actually anything to do with
* JWTs, we just know it's a safe namespace to use, and it means you
* can use JWTs too, if you like, and they'll use the same settings
* names reducing the amount of code you need to write.
*/
"jwt.claims.session_id": sessionId,
};
},
/*
* These properties are merged into context (the third argument to GraphQL
* resolvers). This is useful if you write your own plugins that need
* access to, e.g., the logged in user.
*/
async additionalGraphQLContextFromRequest(req) {
return {
// The current session id
sessionId: req.user && uuidOrNull(req.user.session_id),
// Needed so passport can write to the database
rootPgPool,
// Use this to tell Passport.js we're logged in
login: (user: any) =>
new Promise((resolve, reject) => {
req.login(user, err => (err ? reject(err) : resolve()));
}),
logout: () => {
req.logout();
return Promise.resolve();
},
};
},
// Pro plugin options (requires process.env.GRAPHILE_LICENSE)
defaultPaginationCap:
parseInt(process.env.GRAPHQL_PAGINATION_CAP || "", 10) || 50,
graphqlDepthLimit:
parseInt(process.env.GRAPHQL_DEPTH_LIMIT || "", 10) || 12,
graphqlCostLimit:
parseInt(process.env.GRAPHQL_COST_LIMIT || "", 10) || 30000,
exposeGraphQLCost:
(parseInt(process.env.HIDE_QUERY_COST || "", 10) || 0) < 1,
// readReplicaPgPool ...,
};
return options;
}
export default function installPostGraphile(app: Express) {
const websocketMiddlewares = getWebsocketMiddlewares(app);
const authPgPool = getAuthPgPool(app);
const rootPgPool = getRootPgPool(app);
const middleware = postgraphile<Request, Response>(
authPgPool,
"app_public",
getPostGraphileOptions({
websocketMiddlewares,
rootPgPool,
})
);
app.set("postgraphileMiddleware", middleware);
app.use(middleware);
const httpServer = getHttpServer(app);
if (httpServer) {
enhanceHttpServerWithSubscriptions(httpServer, middleware);
}
}