From ff69a0abdf34ed0aa807f74efa03701d9c006f2d Mon Sep 17 00:00:00 2001 From: Luca Casonato Date: Wed, 2 Jun 2021 00:15:00 +0200 Subject: [PATCH] feat: add api routes (#11) This commit adds API routes. These routes are located in the ./pages/api/ directory. Each file in there will have it's default export invoked for HTTP calls to the corresponding route. --- example/api_deps.ts | 1 + example/pages/api/joke.ts | 20 ++++++++++ example/routes.gen.ts | 10 +++-- src/cli/init.ts | 37 ++++++++++++++++-- src/cli/routes.ts | 2 +- src/server/bundle.ts | 2 +- src/server/mod.ts | 23 +++++++---- src/server/render.ts | 2 +- src/server/router.ts | 12 +++++- src/server/{page.ts => routes.ts} | 64 +++++++++++++++++++++++-------- 10 files changed, 136 insertions(+), 37 deletions(-) create mode 100644 example/api_deps.ts create mode 100644 example/pages/api/joke.ts rename src/server/{page.ts => routes.ts} (59%) diff --git a/example/api_deps.ts b/example/api_deps.ts new file mode 100644 index 00000000..2840fd7f --- /dev/null +++ b/example/api_deps.ts @@ -0,0 +1 @@ +export * from "../server.ts"; diff --git a/example/pages/api/joke.ts b/example/pages/api/joke.ts new file mode 100644 index 00000000..33c0dffa --- /dev/null +++ b/example/pages/api/joke.ts @@ -0,0 +1,20 @@ +import { oak } from "../../api_deps.ts"; + +// Jokes courtesy of https://punsandoneliners.com/randomness/programmer-jokes/ +const JOKES = [ + "Why do Java developers often wear glasses? They can’t C#.", + "A SQL query walks into a bar, goes up to two tables and says “can I join you?", + "Wasn’t hard to crack Forrest Gump’s password. 1forrest1.", + "I love pressing the F5 key. It’s refreshing.", + "Called IT support and a chap from Australia came to fix my network connection. I asked “Do you come from a LAN down under?”", + "There are 10 types of people in the world. Those who understand binary and those who don’t.", + "Why are assembly programmers often wet? They work below C level.", + "My favourite computer based band is the Black IPs.", + "What programme do you use to predict the music tastes of former US presidential candidates? An Al Gore Rhythm.", + "An SEO expert walked into a bar, pub, inn, tavern, hostelry, public house.", +]; + +export default (ctx: oak.Context) => { + const randomIndex = Math.floor(Math.random() * 10); + ctx.response.body = JOKES[randomIndex]; +}; diff --git a/example/routes.gen.ts b/example/routes.gen.ts index 2f296a87..85c56c74 100644 --- a/example/routes.gen.ts +++ b/example/routes.gen.ts @@ -2,13 +2,15 @@ // This file SHOULD be checked into source version control. // To update this file, run `fresh routes`. -import * as $0 from "./pages/[name].tsx"; -import * as $1 from "./pages/index.tsx"; +import * as $0 from "./pages/api/joke.ts"; +import * as $1 from "./pages/[name].tsx"; +import * as $2 from "./pages/index.tsx"; const routes = { pages: { - "./pages/[name].tsx": $0, - "./pages/index.tsx": $1, + "./pages/api/joke.ts": $0, + "./pages/[name].tsx": $1, + "./pages/index.tsx": $2, }, baseUrl: import.meta.url, }; diff --git a/src/cli/init.ts b/src/cli/init.ts index f6bbc299..09a0dd2a 100644 --- a/src/cli/init.ts +++ b/src/cli/init.ts @@ -55,12 +55,17 @@ async function init(directory: string) { } } - await Deno.mkdir(join(directory, "pages"), { recursive: true }); + await Deno.mkdir(join(directory, "pages", "api"), { recursive: true }); const DEPS_TS = `export * from "${new URL( "../../runtime.ts", import.meta.url, )}";\n`; await Deno.writeTextFile(join(directory, "deps.ts"), DEPS_TS); + const API_DEPS_TS = `export * from "${new URL( + "../../server.ts", + import.meta.url, + )}";\n`; + await Deno.writeTextFile(join(directory, "api_deps.ts"), API_DEPS_TS); const PAGES_INDEX_TSX = `import { h, IS_BROWSER, useState } from "../deps.ts"; export default function Home() { @@ -107,6 +112,31 @@ export default function Greet(props: Props) { join(directory, "pages", "[name].tsx"), PAGES_GREET_TSX, ); + const PAGES_API_JOKE_TS = `import { oak } from "../../api_deps.ts"; + +// Jokes courtesy of https://punsandoneliners.com/randomness/programmer-jokes/ +const JOKES = [ + "Why do Java developers often wear glasses? They can’t C#.", + "A SQL query walks into a bar, goes up to two tables and says “can I join you?", + "Wasn’t hard to crack Forrest Gump’s password. 1forrest1.", + "I love pressing the F5 key. It’s refreshing.", + "Called IT support and a chap from Australia came to fix my network connection. I asked “Do you come from a LAN down under?”", + "There are 10 types of people in the world. Those who understand binary and those who don’t.", + "Why are assembly programmers often wet? They work below C level.", + "My favourite computer based band is the Black IPs.", + "What programme do you use to predict the music tastes of former US presidential candidates? An Al Gore Rhythm.", + "An SEO expert walked into a bar, pub, inn, tavern, hostelry, public house.", +]; + +export default (ctx: oak.Context) => { + const randomIndex = Math.floor(Math.random() * 10); + ctx.response.body = JOKES[randomIndex]; +}; +`; + await Deno.writeTextFile( + join(directory, "pages", "api", "joke.ts"), + PAGES_API_JOKE_TS, + ); const TSCONFIG_JSON = JSON.stringify( { "compilerOptions": { @@ -116,7 +146,7 @@ export default function Greet(props: Props) { }, undefined, 2, - ); + ) + "\n"; await Deno.writeTextFile( join(directory, "tsconfig.json"), TSCONFIG_JSON, @@ -132,7 +162,7 @@ start(routes); MAIN_TS, ); const README_MD = `# fresh project - + ### Usage Install deployctl: @@ -152,7 +182,6 @@ After adding, removing, or moving a page in the \`pages\` directory, run: \`\`\` fresh routes \`\`\` - `; await Deno.writeTextFile( join(directory, "README.md"), diff --git a/src/cli/routes.ts b/src/cli/routes.ts index 3c8bc5ef..77e877a4 100644 --- a/src/cli/routes.ts +++ b/src/cli/routes.ts @@ -43,7 +43,7 @@ export async function routes(directory: string) { const folder = walk(pagesDir, { includeDirs: false, includeFiles: true, - exts: ["tsx", "jsx"], + exts: ["tsx", "jsx", "ts", "js"], }); for await (const entry of folder) { if (entry.isFile) { diff --git a/src/server/bundle.ts b/src/server/bundle.ts index be25274f..4b65ef02 100644 --- a/src/server/bundle.ts +++ b/src/server/bundle.ts @@ -1,5 +1,5 @@ import { denoPlugin, esbuild } from "./deps.ts"; -import { Page } from "./page.ts"; +import { Page } from "./routes.ts"; let esbuildInitalized: boolean | Promise = false; async function ensureEsbuildInialized() { diff --git a/src/server/mod.ts b/src/server/mod.ts index 5a2c93bc..4f3ff34f 100644 --- a/src/server/mod.ts +++ b/src/server/mod.ts @@ -1,17 +1,23 @@ import { oak } from "./deps.ts"; -import { Page, PageModule, processRoutes } from "./page.ts"; +import { + ApiRoute, + ApiRouteModule, + Page, + PageModule, + processRoutes, +} from "./routes.ts"; import { installRoutes } from "./router.ts"; export interface Routes { - pages: Record; + pages: Record; baseUrl: string; } -export { installRoutes }; +export { installRoutes, oak }; export function start(routes: Routes) { - const pages = processRoutes(routes); - const app = createDefaultServer(pages); + const [pages, apiRoutes] = processRoutes(routes); + const app = createDefaultServer(pages, apiRoutes); app.addEventListener("error", (err) => { console.error(err.error); }); @@ -19,10 +25,13 @@ export function start(routes: Routes) { addEventListener("fetch", app.fetchEventHandler()); } -export function createDefaultServer(pages: Page[]): oak.Application { +export function createDefaultServer( + pages: Page[], + apiRoutes: ApiRoute[], +): oak.Application { const router = new oak.Router(); - installRoutes(router, pages); + installRoutes(router, pages, apiRoutes); const app = new oak.Application(); diff --git a/src/server/render.ts b/src/server/render.ts index bfe1924e..d2d83063 100644 --- a/src/server/render.ts +++ b/src/server/render.ts @@ -1,6 +1,6 @@ import { renderToString } from "./deps.ts"; import * as rt from "../runtime/deps.ts"; -import { Page } from "./page.ts"; +import { Page } from "./routes.ts"; import { BUILD_ID, INTERNAL_PREFIX, JS_PREFIX } from "./constants.ts"; export function render(page: Page, params: Record): string { diff --git a/src/server/router.ts b/src/server/router.ts index adae2214..65c160ac 100644 --- a/src/server/router.ts +++ b/src/server/router.ts @@ -1,11 +1,15 @@ import { extname, oak } from "./deps.ts"; import { Bundler } from "./bundle.ts"; import { render } from "./render.ts"; -import { Page } from "./page.ts"; +import { ApiRoute, Page } from "./routes.ts"; import { BUILD_ID, INTERNAL_PREFIX, JS_PREFIX } from "./constants.ts"; /** This function installs all routes required by fresh onto an oak router. */ -export function installRoutes(router: oak.Router, pages: Page[]) { +export function installRoutes( + router: oak.Router, + pages: Page[], + apiRoutes: ApiRoute[], +) { for (const page of pages) { router.get>(page.route, (ctx) => { ctx.response.status = 200; @@ -14,6 +18,10 @@ export function installRoutes(router: oak.Router, pages: Page[]) { }); } + for (const apiRoute of apiRoutes) { + router.all(apiRoute.route, apiRoute.handler); + } + const internal = internalRouter(pages); router.use( diff --git a/src/server/page.ts b/src/server/routes.ts similarity index 59% rename from src/server/page.ts rename to src/server/routes.ts index 6e0e6190..816c4969 100644 --- a/src/server/page.ts +++ b/src/server/routes.ts @@ -1,4 +1,4 @@ -import { extname } from "./deps.ts"; +import { extname, oak } from "./deps.ts"; import * as rt from "../runtime/deps.ts"; import { PageProps } from "../runtime/types.ts"; import { Routes } from "./mod.ts"; @@ -14,35 +14,67 @@ export interface Page { component: rt.ComponentType; } +export interface ApiRouteModule { + default: oak.RouterMiddleware>; +} + +export interface ApiRoute { + route: string; + url: string; + name: string; + handler: oak.RouterMiddleware>; +} + /** * Process the routes into individual pages. */ -export function processRoutes(routes: Routes): Page[] { +export function processRoutes(routes: Routes): [Page[], ApiRoute[]] { // Get the routes' base URL. const baseUrl = new URL("./", routes.baseUrl).href; // Extract all pages, and prepare them into this `Page` structure. const pages: Page[] = []; - for (const [self, pageModule] of Object.entries(routes.pages)) { + const apiRoutes: ApiRoute[] = []; + for (const [self, module] of Object.entries(routes.pages)) { const url = new URL(self, baseUrl).href; if (!url.startsWith(baseUrl)) { throw new TypeError("Page is not a child of the basepath."); } const path = url.substring(baseUrl.length).substring("pages".length); - const name = path.substring(1, path.length - extname(path).length); - const route = pathToRoute(name); - const page: Page = { - route, - url, - name: name.replace("/", "-"), - component: pageModule.default, - }; - pages.push(page); + const baseRoute = path.substring(1, path.length - extname(path).length); + const route = pathToRoute(baseRoute); + const name = baseRoute.replace("/", "-"); + if (path.startsWith("/api")) { + const apiRoute: ApiRoute = { + route, + url, + name, + handler: module.default as oak.RouterMiddleware>, + }; + apiRoutes.push(apiRoute); + } else { + const page: Page = { + route, + url, + name, + component: module.default as rt.ComponentType, + }; + pages.push(page); + } } - // Sort pages by theur relative routing priority, based on the parts in the - // route matcher. - pages.sort((a, b) => { + sortRoutes(pages); + sortRoutes(apiRoutes); + + return [pages, apiRoutes]; +} + +/** + * Sort pages by their relative routing priority, based on the parts in the + * route matcher + */ +function sortRoutes(routes: T[]) { + routes.sort((a, b) => { const partsA = a.route.split("/"); const partsB = b.route.split("/"); for (let i = 0; i < Math.max(partsA.length, partsB.length); i++) { @@ -57,8 +89,6 @@ export function processRoutes(routes: Routes): Page[] { } return 0; }); - - return pages; } /** Transform a filesystem URL path to a `path-to-regex` style matcher. */