This repository has been archived by the owner on Feb 29, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.mjs
94 lines (73 loc) · 4.17 KB
/
index.mjs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import fs from 'fs';
import path from 'path';
import { pathToFileURL } from 'url';
// Set current directory
const __dirname = path.resolve();
/* function definitions
* fastify: fastify instance
* options: options {dir: path to routes | log: log to console}
*/
export async function loadRoutes(fastify, options, logger) {
if (!fastify) throw new Error('Fastify not provided');
//Check options
if (!options) throw new Error('No options provided');
if (!options.dir) throw new Error('No home directory provided (example ./src/server/routes/public)');
//Remove trailing slash from dir
if (options.dir.endsWith('/')) options.dir = options.dir.slice(0, -1);
//Check if prefix starts with a slash and remove trailing slash
if (options.prefix) {
if (!options.prefix.startsWith('/')) options.prefix = '/' + options.prefix;
if (options.prefix.endsWith('/')) options.prefix = options.prefix.slice(0, -1);
};
if (options.log) console.log('verbose', 'fastify-router', 'Loading routes...');
const routesPath = path.join(__dirname, `${options.dir}`); //Setting the directory were looding routes from
async function loadFiles(current_location) {
if (!current_location || current_location.length < 1) current_location = routesPath; //if we are at the end of a folder or just starting
const files = fs.readdirSync(current_location); //Load all files
for (const file of files) {
if (fs.statSync(path.join(current_location, file)).isDirectory()) { //if we are on a directory, loads its content
await loadFiles(path.join(current_location, file));
} else {
if (file.endsWith(".js") || file.endsWith(".mjs")) { //if the file is a js or mjs file
let routePath = pathToFileURL(path.resolve(current_location, file)); //Define the current path
let routeHandler = await import(pathToFileURL(path.resolve(current_location, file))); //Import the route handler/function
routeHandler = routeHandler.default; //
//Params parser
let routeExtension = routesPath.split('\\').pop().split('/').pop(); //Get the last part of the path
let routeURL = routePath.pathname.split(`${routeExtension}`)[1];
routeURL = routeURL.replace(/\[/g, ':');
routeURL = routeURL.replace(/\]/g, '');
routeURL = routeURL.replace(/\.js/g, '');
routeURL = routeURL.replace(/\.mjs/g, '');
//REST method parser
let routeMethod = path.basename(routeURL);
if (routeMethod.split('-')[1]) {
routeMethod = routeMethod.split('-')[0];
routeURL = routeURL.replace(`${routeMethod}-`, '');
routeMethod = routeMethod.toUpperCase();
} else {
routeMethod = options.method || 'GET';
};
//Index parser
if (path.basename(routeURL) === 'index') routeURL = path.dirname(routeURL);
//Prefix parser
if (options.prefix) routeURL = `${options.prefix}${routeURL}`;
//If we have all the required information
if (routeHandler && routeURL) {
if (options.log) console.log('verbose', 'fastify-router', `Setting route from '${routeExtension}' as ${routeMethod}:${routeURL}`, );
await fastify.route({ //Set route in fastify
method: routeMethod,
url: routeURL,
handler: routeHandler
});
if (options.log) console.log('verbose', 'fastify-router', `Registered route from '${routeExtension}' as ${routeMethod}:${routeURL} ✅`);
};
};
};
};
};
await loadFiles();
};
export default {
loadRoutes
};