diff --git a/src/lib/__tests__/crunchInterceptor.test.js b/src/lib/__tests__/crunchInterceptor.test.js index 9a88487705..5afbf7fe2a 100644 --- a/src/lib/__tests__/crunchInterceptor.test.js +++ b/src/lib/__tests__/crunchInterceptor.test.js @@ -17,7 +17,8 @@ describe("crunchInterceptor", () => { .get("/?query={greeting}") .set("Accept", "application/json") .expect(200) - .then(() => { + .then(res => { + expect(res.headers).not.toHaveProperty("X-Crunch") expect(intercept).not.toHaveBeenCalled() }) }) @@ -27,8 +28,25 @@ describe("crunchInterceptor", () => { .get("/?query={greeting}&crunch") .set("Accept", "application/json") .expect(200) + .expect("X-Crunch", "true") + .then(res => { + expect(res.body).toMatchObject( + crunch({ data: { greeting: "Hello World" } }) + ) + }) + }) + + it("should crunch the result when header is present", () => { + return request(app(crunchInterceptor)) + .get("/?query={greeting}") + .set("Accept", "application/json") + .set("X-Crunch", true) + .expect(200) + .expect("X-Crunch", "true") .then(res => { - expect(res.body.data).toMatchObject(crunch({ greeting: "Hello World" })) + expect(res.body).toMatchObject( + crunch({ data: { greeting: "Hello World" } }) + ) }) }) @@ -38,7 +56,8 @@ describe("crunchInterceptor", () => { .get("/?query={greeting}&crunch") .set("Accept", "application/json") .expect(404) - .then(() => { + .then(res => { + expect(res.headers).not.toHaveProperty("X-Crunch") expect(intercept).not.toHaveBeenCalled() }) }) diff --git a/src/lib/crunchInterceptor.js b/src/lib/crunchInterceptor.js index faead63d42..e5fba6cdeb 100644 --- a/src/lib/crunchInterceptor.js +++ b/src/lib/crunchInterceptor.js @@ -1,12 +1,14 @@ import { crunch } from "graphql-crunch" import interceptor from "express-interceptor" -export const interceptorCallback = req => ({ - isInterceptable: () => req.query.hasOwnProperty("crunch"), +export const interceptorCallback = (req, res) => ({ + isInterceptable: () => + req.query.hasOwnProperty("crunch") || req.headers["x-crunch"], intercept: (body, send) => { body = JSON.parse(body) // eslint-disable-line no-param-reassign - if (body && body.data) { - body.data = crunch(body.data) // eslint-disable-line no-param-reassign + if (body) { + body = crunch(body) // eslint-disable-line no-param-reassign + res.set("X-Crunch", "true") } send(JSON.stringify(body)) },