@graphql-yoga/plugin-sofa
Version:
74 lines (73 loc) • 3.15 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.useSofa = useSofa;
const sofa_api_1 = require("sofa-api");
function useSofa(config) {
let sofaHandler;
let getEnveloped;
const envelopedByContext = new WeakMap();
const requestByContext = new WeakMap();
return {
onYogaInit({ yoga }) {
getEnveloped = yoga.getEnveloped;
},
onSchemaChange(onSchemaChangeEventPayload) {
sofaHandler = (0, sofa_api_1.useSofa)({
...config,
schema: onSchemaChangeEventPayload.schema,
async context(serverContext) {
const enveloped = getEnveloped(serverContext);
const request = requestByContext.get(serverContext);
const contextValue = await enveloped.contextFactory({ request });
envelopedByContext.set(contextValue, enveloped);
return contextValue;
},
execute(...args) {
const executionArgs = args.length === 1
? args[0]
: {
schema: args[0],
document: args[1],
rootValue: args[2],
contextValue: args[3],
variableValues: args[4],
operationName: args[5],
fieldResolver: args[6],
typeResolver: args[7],
};
const enveloped = envelopedByContext.get(executionArgs.contextValue);
if (!enveloped) {
throw new TypeError('Illegal invocation.');
}
return enveloped.execute(executionArgs);
},
subscribe(...args) {
const subscriptionArgs = args.length === 1
? args[0]
: {
schema: args[0],
document: args[1],
rootValue: args[2],
contextValue: args[3],
variableValues: args[4],
operationName: args[5],
fieldResolver: args[6],
subscribeFieldResolver: args[7],
};
const enveloped = envelopedByContext.get(subscriptionArgs.contextValue);
if (!enveloped) {
throw new TypeError('Illegal invocation.');
}
return enveloped.subscribe(subscriptionArgs);
},
});
},
async onRequest({ request, serverContext, endResponse }) {
requestByContext.set(serverContext, request);
const response = await sofaHandler.handle(request, serverContext);
if (response != null && response.status !== 404) {
endResponse(response);
}
},
};
}