@graphql-yoga/plugin-sofa
Version:
51 lines (50 loc) • 2.02 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.useSofa = void 0;
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 enveloped = envelopedByContext.get(args.contextValue);
if (!enveloped) {
throw new TypeError('Illegal invocation.');
}
return enveloped.execute(args);
},
subscribe(args) {
const enveloped = envelopedByContext.get(args.contextValue);
if (!enveloped) {
throw new TypeError('Illegal invocation.');
}
return enveloped.subscribe(args);
},
});
},
async onRequest({ request, serverContext, endResponse }) {
requestByContext.set(serverContext, request);
const response = await sofaHandler.handle(request, serverContext);
if (response != null && response.status !== 404) {
endResponse(response);
}
},
};
}
exports.useSofa = useSofa;
;