Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add support for edge #82

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
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
1 change: 1 addition & 0 deletions apps/example-todo-app/next-env.d.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
/// <reference types="next/navigation-types/compat/navigation" />

// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.
15 changes: 10 additions & 5 deletions apps/example-todo-app/next.config.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,20 @@
// This file changes the routing to allow top-level prefixes

module.exports = {
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
async rewrites() {
return {
beforeFiles: [
// Nextjs by default requires a /api prefix, let's remove that
{
source: "/:path*",
destination: "/api/:path*",
},
// REVIEW: I was not able to make the redirect work
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I could not make the redirect work, maybe there is some issue with having /app and /pages simultaneously.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yea it's ok to not have /pages and /app simultaneously 👍 we should support app directory but that's non-critical for now

// {
// source: "/:path*",
// destination: "/api/:path*",
// },
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@itelo I think it would be a lot better if we created an example-edge-todo-app instead of modifying the existing one, we can merge them later, but for now changing this file is too difficult because it's not clear if you're introducing a regression

],
}
},
}

module.exports = nextConfig
6 changes: 3 additions & 3 deletions apps/example-todo-app/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,13 @@
"glob-promise": "4.2.2",
"micro": "9.3.4",
"mkdirp": "1.0.4",
"next": "12.2.0",
"next": "^13.4.9",
"nextjs-middleware-wrappers": "^1.3.0",
"nextlove": "*",
"path-to-regexp": "6.2.1",
"raw-body": "2.3.2",
"react": "18.2.0",
"react-dom": "18.2.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"uuid": "^8.3.2",
"zod": "^3.17.3"
},
Expand Down
15 changes: 15 additions & 0 deletions apps/example-todo-app/src/app/edge/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { withRouteSpecEdge } from "@/lib/middlewares"
import { z } from "zod"

export const runtime = "edge"

const route_spec = {
jsonResponse: z.object({
return: z.boolean(),
}),
auth: "none",
} as const

export const GET = withRouteSpecEdge(route_spec)((req) => {
return req.responseEdge.status(200).json({ return: true })
Comment on lines +13 to +14
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe mirroring the interface of non-edge with

Suggested change
export const GET = withRouteSpecEdge(route_spec)((req) => {
return req.responseEdge.status(200).json({ return: true })
export const GET = withRouteSpecEdge(route_spec)((req, res) => {
return res.status(200).json({ return: true })

would be a bit easier to use (since responseEdge is already an artificial construct anyways)?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I just created a PR to solve this, great idea.

#85

this will also make it easier to remove the duplicated code

#86

})
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { UnauthorizedException, MiddlewareEdge } from "nextlove"

export const withAuthTokenEdge: MiddlewareEdge<{
auth: {
authorized_by: "auth_token"
}
}> = (next) => async (req) => {
const authorization = req.headers.get("authorization")

if (authorization?.split("Bearer ")?.[1] !== "auth_token") {
throw new UnauthorizedException({
type: "unauthorized",
message: "Unauthorized",
})
}

req.auth = {
authorized_by: "auth_token",
}

return next(req)
}

export default withAuthTokenEdge
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,4 @@ export const withAuthToken: Middleware<{
return next(req, res)
}

withAuthToken.securitySchema = {
type: "http",
scheme: "bearer",
bearerFormat: "API Token",
}

export default withAuthToken
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { createWithRouteSpec } from "nextlove"
import { createWithRouteSpec, createWithRouteSpecEdge } from "nextlove"
import { withAuthToken } from "./with-auth-token"
import withAuthTokenEdge from "./with-auth-token-edge"
export { checkRouteSpec } from "nextlove"

export const withRouteSpec = createWithRouteSpec({
Expand All @@ -10,6 +11,16 @@ export const withRouteSpec = createWithRouteSpec({
shouldValidateResponses: true,
} as const)

export const withRouteSpecEdge = createWithRouteSpecEdge({
authMiddlewareMap: { auth_token: withAuthTokenEdge },
globalMiddlewares: [],
apiName: "TODO API",
productionServerUrl: "https://example.com",
shouldValidateResponses: true,
addOkStatus: true,
} as const)


export const withRouteSpecWithoutValidateGetRequestBody = createWithRouteSpec({
authMiddlewareMap: { auth_token: withAuthToken },
globalMiddlewares: [],
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {
withRouteSpecWithoutValidateResponse,
checkRouteSpec,
} from "lib/middlewares"
} from "@/lib/middlewares"
import { z } from "zod"
import { v4 as uuidv4 } from "uuid"

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { withRouteSpec } from "lib/middlewares"
import { withRouteSpec } from "@/lib/middlewares"
import { z } from "zod"
import { v4 as uuidv4 } from "uuid"

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { withRouteSpec, checkRouteSpec } from "lib/middlewares"
import { withRouteSpec } from "@/lib/middlewares"
import { z } from "zod"
import { v4 as uuidv4 } from "uuid"

Expand All @@ -8,14 +8,14 @@ export const jsonBody = z.object({
completed: z.boolean().optional().default(false),
})

export const route_spec = checkRouteSpec({
export const route_spec = {
methods: ["POST"],
auth: "auth_token",
jsonBody,
jsonResponse: z.object({
ok: z.boolean(),
}),
})
} as const

export default withRouteSpec(route_spec)(async (req, res) => {
return res.status(200).json({ ok: true })
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { checkRouteSpec, withRouteSpec } from "lib/middlewares"
import { checkRouteSpec, withRouteSpec } from "@/lib/middlewares"
import { NotFoundException } from "nextlove"
import { TODO_ID } from "tests/fixtures"
import { z } from "zod"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { checkRouteSpec, withRouteSpec } from "lib/middlewares"
import { checkRouteSpec, withRouteSpec } from "@/lib/middlewares"
import { NotFoundException } from "nextlove"
import { TODO_ID } from "tests/fixtures"
import { z } from "zod"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { withRouteSpec, checkRouteSpec } from "lib/middlewares"
import { withRouteSpec, checkRouteSpec } from "@/lib/middlewares"
import { z } from "zod"
import { v4 as uuidv4 } from "uuid"
import { HttpException } from "nextlove"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import {
checkRouteSpec,
withRouteSpecWithoutValidateGetRequestBody,
} from "lib/middlewares"
} from "@/lib/middlewares"
import { NotFoundException } from "nextlove"
import { TODO_ID } from "tests/fixtures"
import { z } from "zod"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { checkRouteSpec, withRouteSpec } from "lib/middlewares"
import { checkRouteSpec, withRouteSpec } from "@/lib/middlewares"
import { NotFoundException } from "nextlove"
import { TODO_ID } from "tests/fixtures"
import { z } from "zod"
Expand All @@ -20,7 +20,7 @@ export const route_spec = checkRouteSpec({
ok: z.boolean(),
todo: z.object({
id: z.string().uuid(),
}),
}).optional(),
error: z
.object({
type: z.string(),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { checkRouteSpec, withRouteSpec } from "lib/middlewares"
import { checkRouteSpec, withRouteSpec } from "@/lib/middlewares"
import { NotFoundException } from "nextlove"
import { TODO_ID } from "tests/fixtures"
import { z } from "zod"
Expand All @@ -20,7 +20,7 @@ export const route_spec = checkRouteSpec({
ok: z.boolean(),
todo: z.object({
id: z.string().uuid(),
}),
}).optional(),
error: z
.object({
type: z.string(),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { withRouteSpec } from "lib/middlewares"
import { withRouteSpec } from "@/lib/middlewares"
import { z } from "zod"
import { v4 as uuidv4 } from "uuid"

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { checkRouteSpec, withRouteSpec } from "lib/middlewares"
import { checkRouteSpec, withRouteSpec } from "@/lib/middlewares"
import { z } from "zod"

export const commonParams = z.object({
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { checkRouteSpec, withRouteSpec } from "lib/middlewares"
import { checkRouteSpec, withRouteSpec } from "@/lib/middlewares"
import { z } from "zod"

export const commonParams = z
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { checkRouteSpec, withRouteSpec } from "lib/middlewares"
import { checkRouteSpec, withRouteSpec } from "@/lib/middlewares"
import { z } from "zod"

export const commonParams = z.object({
Expand Down
6 changes: 3 additions & 3 deletions apps/example-todo-app/tests/api/health.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import test from "ava"
import getTestServer from "tests/fixtures/get-test-server"
import getTestServer from "../fixtures/get-test-server"

test("GET /health", async (t) => {
test("GET /api/health", async (t) => {
const { axios } = await getTestServer(t)
const res = await axios.get("/health")
const res = await axios.get("/api/health")

t.truthy(res.data.ok)
})
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ test("POST /todo/add-ignore-invalid-json-response", async (t) => {
axios.defaults.headers.common.Authorization = `Bearer auth_token`

const successfulRes = await axios
.post("/todo/add-ignore-invalid-json-response", { title: "Todo Title" })
.post("/api/todo/add-ignore-invalid-json-response", { title: "Todo Title" })
.catch((err) => err)

t.is(successfulRes.status, 200)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ test("POST /todo/add-invalid-json-response", async (t) => {
axios.defaults.headers.common.Authorization = `Bearer auth_token`

const successfulRes = await axios
.post("/todo/add-invalid-json-response", { title: "Todo Title" })
.post("/api/todo/add-invalid-json-response", { title: "Todo Title" })
.catch((err) => err)

t.is(successfulRes.status, 500)
Expand Down
10 changes: 5 additions & 5 deletions apps/example-todo-app/tests/api/todo/add.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,29 +4,29 @@ import getTestServer from "tests/fixtures/get-test-server"
test("POST /todo/add", async (t) => {
const { axios } = await getTestServer(t)

const noAuthRes = await axios.post("/todo/add").catch((err) => err)
const noAuthRes = await axios.post("/api/todo/add").catch((err) => err)
t.is(noAuthRes.status, 401, "no auth")

const hasErrorStack = Boolean(noAuthRes.response.error.stack)
t.is(hasErrorStack, true)

axios.defaults.headers.common.Authorization = `Bearer auth_token`

const invalidMethodRes = await axios.get("/todo/add").catch((err) => err)
const invalidMethodRes = await axios.get("/api/todo/add").catch((err) => err)
t.is(invalidMethodRes.status, 405, "invalid method")

const invalidBodyParamTypeRes = await axios
.post("/todo/add", { title: true })
.post("/api/todo/add", { title: true })
.catch((err) => err)
t.is(invalidBodyParamTypeRes.status, 400, "bad body")

const nonExistentIdRes = await axios
.post("/todo/add", { invalidParam: "invalidParam" })
.post("/api/todo/add", { invalidParam: "invalidParam" })
.catch((err) => err)
t.is(nonExistentIdRes.status, 400, "invalid param")

const successfulRes = await axios
.post("/todo/add", { title: "Todo Title" })
.post("/api/todo/add", { title: "Todo Title" })
.catch((err) => err)
t.is(successfulRes.status, 200)
})
Original file line number Diff line number Diff line change
Expand Up @@ -7,34 +7,34 @@ test("DELETE /todo/delete-common-params", async (t) => {
const { axios } = await getTestServer(t)

const noAuthRes = await axios
.delete("/todo/delete-common-params")
.delete("/api/todo/delete-common-params")
.catch((err) => err)
t.is(noAuthRes.status, 401, "no auth")

axios.defaults.headers.common.Authorization = `Bearer auth_token`

const invalidMethodRes = await axios
.get("/todo/delete-common-params")
.get("/api/todo/delete-common-params")
.catch((err) => err)
t.is(invalidMethodRes.status, 405, "invalid method")

const invalidIdFormatRes = await axios
.delete("/todo/delete-common-params", { data: { id: "someId" } })
.delete("/api/todo/delete-common-params", { data: { id: "someId" } })
.catch((err) => err)
t.is(invalidIdFormatRes.status, 400, "invalid id format")

const invalidIdTypeRes = await axios
.delete("/todo/delete-common-params", { data: { id: 123 } })
.delete("/api/todo/delete-common-params", { data: { id: 123 } })
.catch((err) => err)
t.is(invalidIdTypeRes.status, 400, "invalid id type")

const nonExistentIdRes = await axios
.delete("/todo/delete-common-params", { data: { id: uuidv4() } })
.delete("/api/todo/delete-common-params", { data: { id: uuidv4() } })
.catch((err) => err)
t.is(nonExistentIdRes.status, 404, "non-existent id")

const successfulRes = await axios
.delete("/todo/delete-common-params", { data: { id: TODO_ID } })
.delete("/api/todo/delete-common-params", { data: { id: TODO_ID } })
.catch((err) => err)
t.is(successfulRes.status, 200)
})
12 changes: 6 additions & 6 deletions apps/example-todo-app/tests/api/todo/delete.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,31 +6,31 @@ import { v4 as uuidv4 } from "uuid"
test("DELETE /todo/delete", async (t) => {
const { axios } = await getTestServer(t)

const noAuthRes = await axios.delete("/todo/delete").catch((err) => err)
const noAuthRes = await axios.delete("/api/todo/delete").catch((err) => err)
t.is(noAuthRes.status, 401, "no auth")

axios.defaults.headers.common.Authorization = `Bearer auth_token`

const invalidMethodRes = await axios.get("/todo/delete").catch((err) => err)
const invalidMethodRes = await axios.get("/api/todo/delete").catch((err) => err)
t.is(invalidMethodRes.status, 405, "invalid method")

const invalidIdFormatRes = await axios
.delete("/todo/delete", { data: { id: "someId" } })
.delete("/api/todo/delete", { data: { id: "someId" } })
.catch((err) => err)
t.is(invalidIdFormatRes.status, 400, "invalid id format")

const invalidIdTypeRes = await axios
.delete("/todo/delete", { data: { id: 123 } })
.delete("/api/todo/delete", { data: { id: 123 } })
.catch((err) => err)
t.is(invalidIdTypeRes.status, 400, "invalid id type")

const nonExistentIdRes = await axios
.delete("/todo/delete", { data: { id: uuidv4() } })
.delete("/api/todo/delete", { data: { id: uuidv4() } })
.catch((err) => err)
t.is(nonExistentIdRes.status, 404, "non-existent id")

const successfulRes = await axios
.delete("/todo/delete", { data: { id: TODO_ID } })
.delete("/api/todo/delete", { data: { id: TODO_ID } })
.catch((err) => err)
t.is(successfulRes.status, 200)
})
Loading
Loading