import { Application } from 'express'; import fs from 'fs'; import path from 'path'; import bodyParser from 'body-parser'; import { OrisonServer } from '.'; function getEndpoints(root: string, folder: string, server: Application) { if (!fs.existsSync(folder)) { return; } const items = fs.readdirSync(folder); items.sort((a, b) => { if (a.startsWith('by-')) { return 1; } if (b.startsWith('by-')) { return -1; } return a.localeCompare(b); }); for (const item of items) { const abs = path.resolve(path.join(folder, item)); if (fs.lstatSync(abs).isDirectory()) { getEndpoints(root, abs, server); } else { if (item.endsWith('.js')) { let originalEndpoint = '/' + abs.substring(root.length + 1).replace(/\\/g, '/'); let endpoint = originalEndpoint.substring(0, originalEndpoint.length - 3); if (endpoint.endsWith('index')) { endpoint = endpoint.substring(0, endpoint.length - 6); } endpoint = endpoint.replace(/by-/g, ':'); const file = require(abs); if (typeof file.post === 'function') { console.log('Initializing API endpoint: POST ' + endpoint); server.post(endpoint, file.post); } if (typeof file.get === 'function') { console.log('Initializing API endpoint: GET ' + endpoint); server.get(endpoint, file.get); } if (typeof file.del === 'function') { console.log('Initializing API endpoint: DELETE ' + endpoint); server.delete(endpoint, file.del); } } } } } export default { initialize(orison: OrisonServer) { const server = orison.getRequestListener(); server.use('/api/*', bodyParser.json()); getEndpoints(path.resolve('.orison'), '.orison/api', server); server.all('/api/*', (req, res) => { res.sendStatus(404); }); } }