@shopify/koa-shopify-graphql-proxy
Version:
A wrapper around `koa-better-http-proxy` which allows easy proxying of GraphQL requests from an embedded Shopify app
61 lines (54 loc) • 2.15 kB
JavaScript
;
Object.defineProperty(exports, '__esModule', { value: true });
var proxy = require('koa-better-http-proxy');
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
var proxy__default = /*#__PURE__*/_interopDefaultLegacy(proxy);
const PROXY_BASE_PATH = '/graphql';
const GRAPHQL_PATH_PREFIX = '/admin/api';
function shopifyGraphQLProxy(proxyOptions) {
return async function shopifyGraphQLProxyMiddleware(ctx, next) {
const {
session = {}
} = ctx;
const shop = 'shop' in proxyOptions ? proxyOptions.shop : session.shop;
const accessToken = 'password' in proxyOptions ? proxyOptions.password : session.accessToken;
const version = proxyOptions.version;
if (ctx.path !== PROXY_BASE_PATH || ctx.method !== 'POST') {
await next();
return;
}
if (accessToken == null || shop == null) {
ctx.throw(403, 'Unauthorized');
}
await proxy__default["default"](shop, {
https: true,
parseReqBody: false,
// Setting request header here, not response. That's why we don't use ctx.set()
// proxy middleware will grab this request header
/* eslint-disable @typescript-eslint/naming-convention */
headers: {
'Content-Type': 'application/json',
'X-Shopify-Access-Token': accessToken
},
/* eslint-enable @typescript-eslint/naming-convention */
proxyReqOptDecorator(proxyReqOpts) {
delete proxyReqOpts.headers.cookie;
delete proxyReqOpts.headers.Cookie;
return proxyReqOpts;
},
proxyReqPathResolver() {
return `${GRAPHQL_PATH_PREFIX}/${version}/graphql.json`;
}
})(ctx,
/*
We want this middleware to terminate, not fall through to the next in the chain,
but sadly it doesn't support not passing a `next` function. To get around this we
just pass our own dummy `next` that resolves immediately.
*/
noop);
};
}
async function noop() {}
exports.GRAPHQL_PATH_PREFIX = GRAPHQL_PATH_PREFIX;
exports.PROXY_BASE_PATH = PROXY_BASE_PATH;
exports["default"] = shopifyGraphQLProxy;