Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 22 additions & 3 deletions src/lib/__tests__/crunchInterceptor.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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()
})
})
Expand All @@ -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" } })
)
})
})

Expand All @@ -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()
})
})
Expand Down
10 changes: 6 additions & 4 deletions src/lib/crunchInterceptor.js
Original file line number Diff line number Diff line change
@@ -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))
},
Expand Down