Skip to content

Commit

Permalink
add rewrite rule test, fix startup problem
Browse files Browse the repository at this point in the history
  • Loading branch information
magnattic committed Feb 11, 2021
1 parent ed3b865 commit 9b224f8
Show file tree
Hide file tree
Showing 5 changed files with 95 additions and 25 deletions.
3 changes: 2 additions & 1 deletion deps.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,4 +11,5 @@ export { extname } from 'https://deno.land/[email protected]/path/mod.ts';
export { brightGreen } from 'https://deno.land/[email protected]/fmt/colors.ts';
export type { Evt } from 'https://deno.land/x/evt/mod.ts';
import sample from 'https://dev.jspm.io/lodash-es/sample';
export { sample };
import isEqual from 'https://dev.jspm.io/lodash-es/isEqual';
export { sample, isEqual };
32 changes: 32 additions & 0 deletions findPathInDb.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { JsonDB } from './server.ts';

export const findPathInDb = (
db: JsonDB,
routePaths: string[],
rewriteRules?: Record<string, string[]>
) => {
const matchedRewriteKey =
rewriteRules &&
Object.keys(rewriteRules).find(
(rewriteKey) => rewriteKey === routePaths.join('/')
);
const appliedRoutePaths = matchedRewriteKey
? rewriteRules![matchedRewriteKey]
: routePaths;
return appliedRoutePaths.reduce((subDB, routePart) => {
if (routePart == null || routePart === '') {
return subDB;
}
const id = Number(routePart);
if (Array.isArray(subDB) && id !== NaN) {
return (subDB as { id: number }[]).find(
(item) => item.id === id
) as Record<string, unknown>;
}
if (routePart && routePart in subDB) {
return subDB[routePart] as Record<string, unknown>;
}
console.error(`${routePart} not found in ${JSON.stringify(subDB)}!`);
return subDB;
}, db);
};
39 changes: 39 additions & 0 deletions findPathInDb_test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { assertEquals } from 'https://deno.land/[email protected]/testing/asserts.ts';
import { findPathInDb } from './findPathInDb.ts';

const { test } = Deno;

test({
name: 'match simple path',
fn: () => {
const db = { test: { levelTwo: '1' } };

const matched = findPathInDb(db, ['test', 'levelTwo']);

assertEquals(matched, '1');
},
});

test({
name: 'match ids',
fn: () => {
const db = { test: { id: 3, levelTwo: '1' } };

const matched = findPathInDb(db, ['test', '3']);

assertEquals(matched, { id: 3, levelTwo: '1' });
},
});

test({
name: 'match simple rewritten path',
fn: () => {
const db = { test: { levelTwo: '1' } };

const matched = findPathInDb(db, ['yolo'], {
yolo: ['test', 'levelTwo'],
});

assertEquals(matched, '1');
},
});
32 changes: 12 additions & 20 deletions handleRequest.ts
Original file line number Diff line number Diff line change
@@ -1,29 +1,21 @@
import { ServerRequest } from './deps.ts';
import { findPathInDb } from './findPathInDb.ts';
import { JsonDB, RewriteRules } from './server.ts';

export const handleRequest = (db: Record<string, unknown>) => (
export const handleRequest = (db: JsonDB, rewriteRules?: RewriteRules) => (
request: ServerRequest
) => {
const [, ...routePaths] = request.url.split('/');
const isFile = routePaths[routePaths.length - 1].includes('.');
if (isFile) {
request.respond({
status: 404,
body: 'Files are not yet handled',
});
return;
}

const resource = routePaths.reduce<Record<string, unknown>>(
(subDB, routePart) => {
if (routePart == null || routePart === '') {
return subDB;
}
const id = Number(routePart);
if (Array.isArray(subDB) && id !== NaN) {
return (subDB as { id: number }[]).find(
(item) => item.id === id
) as Record<string, unknown>;
}
if (routePart && routePart in subDB) {
return subDB[routePart] as Record<string, unknown>;
}
console.error(`${routePart} not found in ${JSON.stringify(subDB)}!`);
return subDB;
},
db
);
const resource = findPathInDb(db, routePaths, rewriteRules);

const origin = request.headers.get('origin');
const headers = new Headers({
Expand Down
14 changes: 10 additions & 4 deletions server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { handleRequest } from './handleRequest.ts';
import { listenAndServe } from './listenAndServe.ts';

export type JsonDB = Record<string, unknown>;
export type RewriteRules = Record<string, string[]>;

const isString = (value: unknown) =>
typeof value === 'string' || value instanceof String;
Expand All @@ -12,25 +13,30 @@ export interface Options {
dbPathOrObject: string | JsonDB;
port: number;
watchDB: boolean;
rewriteRules: RewriteRules;
}

const defaultOptions: Options = {
dbPathOrObject: './db.json',
port: 8000,
watchDB: true,
rewriteRules: { yolo: ['profile', 'user'] },
};

export const jsonServer = async (options: Partial<Options>) => {
const { dbPathOrObject, port, watchDB } = { ...defaultOptions, ...options };
const { dbPathOrObject, port, watchDB, rewriteRules } = {
...defaultOptions,
...options,
};

let handler = (req: ServerRequest) => {
req.respond({ body: 'loading...' });
};
const server = listenAndServe({ port }, (req) => handler(req));
console.log(`JSON server is running on Port ${port}`);

const handleNewDb = (db: Object) => {
handler = handleRequest(db as Record<string, unknown>);
const handleNewDb = (db: JsonDB) => {
handler = handleRequest(db, rewriteRules);
};
const aborter = new AbortController();
const { signal } = aborter;
Expand Down Expand Up @@ -80,7 +86,7 @@ if (import.meta.main) {
port: cliArgs.port,
watchDB: cliArgs.watchDB,
});
if (cliArgs) {
if (cliArgs.testRun) {
console.log('testRun flag detected, closing the server...');
await new Promise((resolve) => setTimeout(resolve, 1000));
server.close();
Expand Down

0 comments on commit 9b224f8

Please sign in to comment.