UNPKG

graphile-test

Version:
47 lines (46 loc) 1.85 kB
import { graphql, print } from 'graphql'; import { withPostGraphileContext } from 'postgraphile'; // @ts-ignore import MockReq from 'mock-req'; export 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 MockReq({ 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 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 : print(query); const result = await graphql({ schema, source: printed, contextValue: { ...context, pgClient }, variableValues: variables ?? null }); return result; }); }; // IS THIS BAD TO HAVE ROLE HERE export 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)]); } }