Skip to content
Open
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
12 changes: 12 additions & 0 deletions src/create-with-winter-spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,18 @@ function serializeToResponse(
throw new Error("Unknown Response type")
}

// Allow routes to return a plain object instead of WinterSpecJsonResponse.
// e.g. `return { ok: true }` is equivalent to `return new WinterSpecJsonResponse({ ok: true })`.
if (
response !== null &&
typeof response === "object" &&
!(response instanceof Response)
) {
return new WinterSpecJsonResponse(response as any).serializeToResponse(
routeSpec.jsonResponse ?? z.any()
)
}

return response
}

Expand Down
77 changes: 77 additions & 0 deletions tests/endpoints/plain-object-return.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import test from "ava"
import { z } from "zod"
import { getTestRoute } from "../fixtures/get-test-route.js"

test("plain-object-return: GET route returning plain object is serialized as JSON", async (t) => {
const { axios } = await getTestRoute(t, {
globalSpec: {
apiName: "hello-world",
productionServerUrl: "https://example.com",
authMiddleware: {},
beforeAuthMiddleware: [],
},
routeSpec: {
auth: "none",
methods: ["GET"],
},
routePath: "/health",
routeFn: async (_req: any): Promise<any> => {
return { ok: true }
},
})

const { data, status } = await axios.get("/health")
t.is(status, 200)
t.is(data.ok, true)
})

test("plain-object-return: POST route returning plain object with multiple fields", async (t) => {
const { axios } = await getTestRoute(t, {
globalSpec: {
apiName: "hello-world",
productionServerUrl: "https://example.com",
authMiddleware: {},
beforeAuthMiddleware: [],
},
routeSpec: {
auth: "none",
methods: ["POST"],
jsonResponse: z.object({
message: z.string(),
count: z.number(),
}),
},
routePath: "/items",
routeFn: async (_req: any): Promise<any> => {
return { message: "created", count: 42 }
},
})

const { data, status } = await axios.post("/items")
t.is(status, 200)
t.is(data.message, "created")
t.is(data.count, 42)
})

test("plain-object-return: plain object validates against jsonResponse schema", async (t) => {
const { axios } = await getTestRoute(t, {
globalSpec: {
apiName: "hello-world",
productionServerUrl: "https://example.com",
authMiddleware: {},
beforeAuthMiddleware: [],
},
routeSpec: {
auth: "none",
methods: ["GET"],
jsonResponse: z.object({ ok: z.boolean() }),
},
routePath: "/check",
routeFn: async (_req: any): Promise<any> => {
return { ok: true }
},
})

const { data } = await axios.get("/check")
t.is(data.ok, true)
})