-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathhandler.js
64 lines (61 loc) · 2.54 KB
/
handler.js
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
'use strict';
const fs = require('fs');
const PgCatalogBuilder = require('postgraphql/build/postgres/introspection/PgCatalog');
const createPostGraphQLSchema = require('postgraphql/build/postgraphql/schema/createPostGraphQLSchema');
const graphql = require('graphql').graphql;
const Client = require('pg').Client;
const pgClientFromContext = require("postgraphql/build/postgres/inventory/pgClientFromContext");
const setupRequestPgClientTransaction = require("postgraphql/build/postgraphql/http/setupRequestPgClientTransaction");
const PgCat = JSON.parse(fs.readFileSync('pgCatalog/pgCatalog.json', 'utf8'));
module.exports.graphql = (event, context, cb) => {
// Setup connection to PostgresDB
const pgClient = new Client(process.env.PGCON);
pgClient.connect();
// Parse PgCatalog
const PgCatalog = new PgCatalogBuilder.default(PgCat);
// Set postgraphql options
// For all options see https://github.com/calebmer/postgraphql/blob/master/docs/library.md
const options = {
pgDefaultRole: "forum_example_anonymous",
jwtSecret: process.env.JWT_SECRET,
jwtPgTypeIdentifier: "forum_example.jwt_token",
pgDefaultRole: "forum_example_anonymous"
}
let gqlSchema
createPostGraphQLSchema.default(pgClient, PgCatalog, options)
.then((schema) => {
try {
gqlSchema = schema;
// To be honest i am not 100% that the following
// proppery uses 'begin' ... 'commit'
pgClient.query('begin').then( () => {
setupRequestPgClientTransaction.default(event, pgClient, {
jwtSecret: options.jwtSecret,
pgDefaultRole: options.pgDefaultRole
})
.then( (pgRole) => {
graphql(gqlSchema, event.query, null,
{[pgClientFromContext.$$pgClient]: pgClient},
event.variables, event.operationName)
.then((response) => {
pgClient.end();
cb(null, response)
})
.catch(() => cb(e));
})
.then(() => pgClient.query('commit'))
.catch( (err) => {
pgClient.end();
cb(null, {"errors": [err]});
});
})
} catch(err) {
pgClient.end();
cb(null, {"errors": [err]});
}
})
.catch( (err) => {
pgClient.end();
cb(null, {"errors": [err]});
});
}