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.
This commit is contained in:
Luca Casonato
2021-06-02 00:15:00 +02:00
committed by GitHub
parent 31dbd99bea
commit ff69a0abdf
10 changed files with 136 additions and 37 deletions
+1
View File
@@ -0,0 +1 @@
export * from "../server.ts";
+20
View File
@@ -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];
};
+6 -4
View File
@@ -2,13 +2,15 @@
// This file SHOULD be checked into source version control. // This file SHOULD be checked into source version control.
// To update this file, run `fresh routes`. // To update this file, run `fresh routes`.
import * as $0 from "./pages/[name].tsx"; import * as $0 from "./pages/api/joke.ts";
import * as $1 from "./pages/index.tsx"; import * as $1 from "./pages/[name].tsx";
import * as $2 from "./pages/index.tsx";
const routes = { const routes = {
pages: { pages: {
"./pages/[name].tsx": $0, "./pages/api/joke.ts": $0,
"./pages/index.tsx": $1, "./pages/[name].tsx": $1,
"./pages/index.tsx": $2,
}, },
baseUrl: import.meta.url, baseUrl: import.meta.url,
}; };
+33 -4
View File
@@ -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( const DEPS_TS = `export * from "${new URL(
"../../runtime.ts", "../../runtime.ts",
import.meta.url, import.meta.url,
)}";\n`; )}";\n`;
await Deno.writeTextFile(join(directory, "deps.ts"), DEPS_TS); 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"; const PAGES_INDEX_TSX = `import { h, IS_BROWSER, useState } from "../deps.ts";
export default function Home() { export default function Home() {
@@ -107,6 +112,31 @@ export default function Greet(props: Props) {
join(directory, "pages", "[name].tsx"), join(directory, "pages", "[name].tsx"),
PAGES_GREET_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( const TSCONFIG_JSON = JSON.stringify(
{ {
"compilerOptions": { "compilerOptions": {
@@ -116,7 +146,7 @@ export default function Greet(props: Props) {
}, },
undefined, undefined,
2, 2,
); ) + "\n";
await Deno.writeTextFile( await Deno.writeTextFile(
join(directory, "tsconfig.json"), join(directory, "tsconfig.json"),
TSCONFIG_JSON, TSCONFIG_JSON,
@@ -132,7 +162,7 @@ start(routes);
MAIN_TS, MAIN_TS,
); );
const README_MD = `# fresh project const README_MD = `# fresh project
### Usage ### Usage
Install deployctl: Install deployctl:
@@ -152,7 +182,6 @@ After adding, removing, or moving a page in the \`pages\` directory, run:
\`\`\` \`\`\`
fresh routes fresh routes
\`\`\` \`\`\`
`; `;
await Deno.writeTextFile( await Deno.writeTextFile(
join(directory, "README.md"), join(directory, "README.md"),
+1 -1
View File
@@ -43,7 +43,7 @@ export async function routes(directory: string) {
const folder = walk(pagesDir, { const folder = walk(pagesDir, {
includeDirs: false, includeDirs: false,
includeFiles: true, includeFiles: true,
exts: ["tsx", "jsx"], exts: ["tsx", "jsx", "ts", "js"],
}); });
for await (const entry of folder) { for await (const entry of folder) {
if (entry.isFile) { if (entry.isFile) {
+1 -1
View File
@@ -1,5 +1,5 @@
import { denoPlugin, esbuild } from "./deps.ts"; import { denoPlugin, esbuild } from "./deps.ts";
import { Page } from "./page.ts"; import { Page } from "./routes.ts";
let esbuildInitalized: boolean | Promise<void> = false; let esbuildInitalized: boolean | Promise<void> = false;
async function ensureEsbuildInialized() { async function ensureEsbuildInialized() {
+16 -7
View File
@@ -1,17 +1,23 @@
import { oak } from "./deps.ts"; 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"; import { installRoutes } from "./router.ts";
export interface Routes { export interface Routes {
pages: Record<string, PageModule>; pages: Record<string, PageModule | ApiRouteModule>;
baseUrl: string; baseUrl: string;
} }
export { installRoutes }; export { installRoutes, oak };
export function start(routes: Routes) { export function start(routes: Routes) {
const pages = processRoutes(routes); const [pages, apiRoutes] = processRoutes(routes);
const app = createDefaultServer(pages); const app = createDefaultServer(pages, apiRoutes);
app.addEventListener("error", (err) => { app.addEventListener("error", (err) => {
console.error(err.error); console.error(err.error);
}); });
@@ -19,10 +25,13 @@ export function start(routes: Routes) {
addEventListener("fetch", app.fetchEventHandler()); 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(); const router = new oak.Router();
installRoutes(router, pages); installRoutes(router, pages, apiRoutes);
const app = new oak.Application(); const app = new oak.Application();
+1 -1
View File
@@ -1,6 +1,6 @@
import { renderToString } from "./deps.ts"; import { renderToString } from "./deps.ts";
import * as rt from "../runtime/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"; import { BUILD_ID, INTERNAL_PREFIX, JS_PREFIX } from "./constants.ts";
export function render(page: Page, params: Record<string, string>): string { export function render(page: Page, params: Record<string, string>): string {
+10 -2
View File
@@ -1,11 +1,15 @@
import { extname, oak } from "./deps.ts"; import { extname, oak } from "./deps.ts";
import { Bundler } from "./bundle.ts"; import { Bundler } from "./bundle.ts";
import { render } from "./render.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"; import { BUILD_ID, INTERNAL_PREFIX, JS_PREFIX } from "./constants.ts";
/** This function installs all routes required by fresh onto an oak router. */ /** 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) { for (const page of pages) {
router.get<Record<string, string>>(page.route, (ctx) => { router.get<Record<string, string>>(page.route, (ctx) => {
ctx.response.status = 200; 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); const internal = internalRouter(pages);
router.use( router.use(
+47 -17
View File
@@ -1,4 +1,4 @@
import { extname } from "./deps.ts"; import { extname, oak } from "./deps.ts";
import * as rt from "../runtime/deps.ts"; import * as rt from "../runtime/deps.ts";
import { PageProps } from "../runtime/types.ts"; import { PageProps } from "../runtime/types.ts";
import { Routes } from "./mod.ts"; import { Routes } from "./mod.ts";
@@ -14,35 +14,67 @@ export interface Page {
component: rt.ComponentType<PageProps>; component: rt.ComponentType<PageProps>;
} }
export interface ApiRouteModule {
default: oak.RouterMiddleware<Record<string, string>>;
}
export interface ApiRoute {
route: string;
url: string;
name: string;
handler: oak.RouterMiddleware<Record<string, string>>;
}
/** /**
* Process the routes into individual pages. * Process the routes into individual pages.
*/ */
export function processRoutes(routes: Routes): Page[] { export function processRoutes(routes: Routes): [Page[], ApiRoute[]] {
// Get the routes' base URL. // Get the routes' base URL.
const baseUrl = new URL("./", routes.baseUrl).href; const baseUrl = new URL("./", routes.baseUrl).href;
// Extract all pages, and prepare them into this `Page` structure. // Extract all pages, and prepare them into this `Page` structure.
const pages: Page[] = []; 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; const url = new URL(self, baseUrl).href;
if (!url.startsWith(baseUrl)) { if (!url.startsWith(baseUrl)) {
throw new TypeError("Page is not a child of the basepath."); throw new TypeError("Page is not a child of the basepath.");
} }
const path = url.substring(baseUrl.length).substring("pages".length); const path = url.substring(baseUrl.length).substring("pages".length);
const name = path.substring(1, path.length - extname(path).length); const baseRoute = path.substring(1, path.length - extname(path).length);
const route = pathToRoute(name); const route = pathToRoute(baseRoute);
const page: Page = { const name = baseRoute.replace("/", "-");
route, if (path.startsWith("/api")) {
url, const apiRoute: ApiRoute = {
name: name.replace("/", "-"), route,
component: pageModule.default, url,
}; name,
pages.push(page); handler: module.default as oak.RouterMiddleware<Record<string, string>>,
};
apiRoutes.push(apiRoute);
} else {
const page: Page = {
route,
url,
name,
component: module.default as rt.ComponentType<PageProps>,
};
pages.push(page);
}
} }
// Sort pages by theur relative routing priority, based on the parts in the sortRoutes(pages);
// route matcher. sortRoutes(apiRoutes);
pages.sort((a, b) => {
return [pages, apiRoutes];
}
/**
* Sort pages by their relative routing priority, based on the parts in the
* route matcher
*/
function sortRoutes<T extends { route: string }>(routes: T[]) {
routes.sort((a, b) => {
const partsA = a.route.split("/"); const partsA = a.route.split("/");
const partsB = b.route.split("/"); const partsB = b.route.split("/");
for (let i = 0; i < Math.max(partsA.length, partsB.length); i++) { 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 0;
}); });
return pages;
} }
/** Transform a filesystem URL path to a `path-to-regex` style matcher. */ /** Transform a filesystem URL path to a `path-to-regex` style matcher. */