UNPKG

852 BJavaScriptView Raw
1const fs = require('fs');
2const path = require('path');
3const { validate } = require('./options');
4
5module.exports = folder => {
6 // Read folder to list endpoints of API ('/src/api/{folder}/*')
7 const endpoints = fs
8 .readdirSync(path.resolve(__dirname, '../api', folder))
9 .map(i => i.slice(0, -3));
10
11 // Load each endpoint file
12 const api = {};
13 for (const endpoint of endpoints)
14 api[endpoint] = require(path.resolve(
15 __dirname,
16 '../api',
17 folder,
18 endpoint
19 ));
20
21 // Initialize each endpoint
22 const init = (options = {}) => {
23 const { error } = validate(options);
24 if (error) throw new Error(error.details[0].message);
25
26 const initialized = {};
27 for (const endpoint of endpoints)
28 initialized[endpoint] = api[endpoint](options);
29
30 return initialized;
31 };
32
33 return { init, ...api };
34};