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 -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. */