This commit is contained in:
39
index.ts
Normal file
39
index.ts
Normal file
@@ -0,0 +1,39 @@
|
||||
import express from 'express';
|
||||
import path from 'path';
|
||||
import { readdir } from 'node:fs/promises';
|
||||
|
||||
import { config } from './config';
|
||||
|
||||
const app = express();
|
||||
|
||||
async function loadPages(): Promise<void> {
|
||||
try {
|
||||
const pagesPath = path.join(__dirname, './pages');
|
||||
const pagesFiles = path.basename(__filename).endsWith('.ts')
|
||||
? (await readdir(pagesPath)).filter(file => file.endsWith('.ts'))
|
||||
: (await readdir(pagesPath)).filter(file => file.endsWith('.js'));
|
||||
for (const file of pagesFiles) {
|
||||
const filePath = path.join(pagesPath, file);
|
||||
const data = await import(filePath);
|
||||
if (data.page !== undefined)
|
||||
app.get(data.page.path, data.page.handleRequest);
|
||||
else
|
||||
console.error(`The page at ${filePath} is missing required properties.`);
|
||||
}
|
||||
} catch(err: unknown) { throw err; }
|
||||
}
|
||||
|
||||
async function init() {
|
||||
try {
|
||||
await loadPages();
|
||||
app.listen(config.port, () => {
|
||||
console.log(`api server up, listen on ${config.port}`);
|
||||
});
|
||||
} catch(err: unknown) { throw err; }
|
||||
}
|
||||
|
||||
try { init(); } catch(err: unknown) {
|
||||
if (err instanceof Error)
|
||||
console.error(`Error, ${err.message}`);
|
||||
console.error(`Error, ${String(err)}`);
|
||||
}
|
||||
Reference in New Issue
Block a user