graphile-test
Version:
PostGraphile Testing
55 lines (54 loc) • 2.27 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.runGraphQLInContext = void 0;
exports.setContextOnClient = setContextOnClient;
const graphql_1 = require("graphql");
const postgraphile_1 = require("postgraphile");
// @ts-ignore
const mock_req_1 = __importDefault(require("mock-req"));
const runGraphQLInContext = async ({ input, conn, pgPool, schema, options, authRole, query, variables, reqOptions = {} }) => {
if (!conn.pg.client) {
throw new Error('pgClient is required and must be provided externally.');
}
const req = new mock_req_1.default({
url: options.graphqlRoute || '/graphql',
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
...reqOptions
});
const pgSettingsGenerator = options.pgSettings;
// @ts-ignore
const pgSettings = typeof pgSettingsGenerator === 'function'
? await pgSettingsGenerator(req)
: pgSettingsGenerator || {};
// @ts-ignore
return await (0, postgraphile_1.withPostGraphileContext)({ ...options, pgPool, pgSettings }, async (context) => {
const pgConn = input.useRoot ? conn.pg : conn.db;
const pgClient = pgConn.client;
// IS THIS BAD TO HAVE ROLE HERE
await setContextOnClient(pgClient, pgSettings, authRole);
await pgConn.ctxQuery();
const printed = typeof query === 'string' ? query : (0, graphql_1.print)(query);
const result = await (0, graphql_1.graphql)({
schema,
source: printed,
contextValue: { ...context, pgClient },
variableValues: variables ?? null
});
return result;
});
};
exports.runGraphQLInContext = runGraphQLInContext;
// IS THIS BAD TO HAVE ROLE HERE
async function setContextOnClient(pgClient, pgSettings, role) {
await pgClient.query(`select set_config('role', $1, true)`, [role]);
for (const [key, value] of Object.entries(pgSettings)) {
await pgClient.query(`select set_config($1, $2, true)`, [key, String(value)]);
}
}