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
+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(
"../../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"),
+1 -1
View File
@@ -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) {
+1 -1
View File
@@ -1,5 +1,5 @@
import { denoPlugin, esbuild } from "./deps.ts";
import { Page } from "./page.ts";
import { Page } from "./routes.ts";
let esbuildInitalized: boolean | Promise<void> = false;
async function ensureEsbuildInialized() {
+16 -7
View File
@@ -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<string, PageModule>;
pages: Record<string, PageModule | ApiRouteModule>;
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();
+1 -1
View File
@@ -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, string>): string {
+10 -2
View File
@@ -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<Record<string, string>>(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(
+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 { PageProps } from "../runtime/types.ts";
import { Routes } from "./mod.ts";
@@ -14,35 +14,67 @@ export interface Page {
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.
*/
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<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
// 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<T extends { route: string }>(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. */