UNPKG

@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

51 lines (48 loc) 1.81 kB
import proxy from 'koa-better-http-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(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() {} export { GRAPHQL_PATH_PREFIX, PROXY_BASE_PATH, shopifyGraphQLProxy as default };