graphql-yoga
Version:
<div align="center"><img src="./website/public/cover.png" width="720" /></div>
36 lines (35 loc) • 1.5 kB
JavaScript
import { handleMaybePromise } from '@whatwg-node/promise-helpers';
/**
* Adds a readiness check for Yoga by simply implementing the `check` option.
*/
export function useReadinessCheck({ endpoint = '/ready', check, }) {
let urlPattern;
return {
onYogaInit({ yoga }) {
urlPattern = new yoga.fetchAPI.URLPattern({ pathname: endpoint });
},
onRequest({ request, endResponse, fetchAPI, url }) {
if (request.url.endsWith(endpoint) || url.pathname === endpoint || urlPattern.test(url)) {
return handleMaybePromise(() => check({ request, fetchAPI }), readyOrResponse => {
let response;
if (typeof readyOrResponse === 'object') {
response = readyOrResponse;
}
else {
response = new fetchAPI.Response(null, {
status: readyOrResponse === false ? 503 : 200,
});
}
endResponse(response);
}, err => {
const isError = err instanceof Error;
const response = new fetchAPI.Response(isError ? err.message : null, {
status: 503,
headers: isError ? { 'content-type': 'text/plain; charset=utf-8' } : {},
});
endResponse(response);
});
}
},
};
}