rjweb-server
Version:
Easy and Robust Way to create a Web Server with Many Easy-to-use Features in NodeJS
161 lines (160 loc) • 4.63 kB
JavaScript
import { isRegExp } from "util/types";
import parsePath from "../../functions/parsePath";
import RouteWS from "./ws";
import RouteHTTP from "./http";
import RouteDefaultHeaders from "./defaultHeaders";
class RouteFile {
/**
* Create a new Route File
* @example
* ```
* // routes/say.js
* module.exports = new controller.routeFile((file) => file
* .http('GET', '/say/<text>', (http) => http
* .onRequest((ctr) => {
* ctr.print(ctr.params.get('text'))
* })
* )
* )
*
* // index.js
* const controller = new Server({ })
*
* controller.path('/', (path) => path
* .loadCJS('./routes')
* )
* ```
* @since 6.0.0
*/
constructor(code) {
this.routes = [];
this.webSockets = [];
this.headers = {};
this.parsedHeaders = {};
this.validations = [];
this.externals = [];
this.hasCalledGet = false;
code(this);
}
/**
* Add a Validation
* @example
* ```
* // The /api route will automatically check for correct credentials
* // Obviously still putting the prefix (in this case / from the RoutePath in front)
* const controller = new Server({ })
*
* module.exports = new controller.routeFile((file) => file
* .validate(async(ctr) => {
* if (!ctr.headers.has('Authorization')) return end(ctr.status(401).print('Unauthorized'))
* if (ctr.headers.get('Authorization') !== 'key123 or db request ig') return end(ctr.status(401).print('Unauthorized'))
* })
* .redirect('/pics', 'https://google.com/search?q=devil')
* )
* ```
* @since 6.0.2
*/
validate(code) {
this.validations.push(code);
return this;
}
/**
* Add Default Headers
* @example
* ```
* module.exports = new controller.routeFile((file) => file
* .defaultHeaders((dH) => dH
* .add('X-Api-Version', '1.0.0')
* )
* )
* ```
* @since 6.0.1
*/
defaultHeaders(code) {
const routeDefaultHeaders = new RouteDefaultHeaders();
this.externals.push({ object: routeDefaultHeaders });
code(routeDefaultHeaders);
this.headers = Object.assign(this.headers, routeDefaultHeaders["defaultHeaders"]);
return this;
}
/**
* Add a HTTP Route
* @example
* ```
* module.exports = new controller.routeFile((file) => file
* .http('GET', '/hello', (ws) => ws
* .onRequest(async(ctr) => {
* ctr.print('Hello bro!')
* })
* )
* )
* ```
* @since 6.0.0
*/
http(method, path, callback) {
if (this.routes.some((obj) => isRegExp(obj.path) ? false : obj.path.path === parsePath(path)))
return this;
const routeHTTP = new RouteHTTP(isRegExp(path) ? path : parsePath(path), method, this.validations, this.parsedHeaders);
this.externals.push({ object: routeHTTP });
callback(routeHTTP);
return this;
}
/**
* Add a Websocket Route
* @example
* ```
* module.exports = new controller.routeFile((file) => file
* .ws('/uptime', (ws) => ws
* .onConnect(async(ctr) => {
* console.log('Connected to ws!')
* })
* .onMessage((ctr) => {
* console.log('Received message', ctr.message)
* })
* .onClose((ctr) => {
* console.log('Disconnected from ws!')
* })
* )
* )
* ```
* @since 5.4.0
*/
ws(path, callback) {
if (this.webSockets.some((obj) => isRegExp(obj.path) ? false : obj.path.path === parsePath(path)))
return this;
const routeWS = new RouteWS(isRegExp(path) ? path : parsePath(path), this.validations, this.parsedHeaders);
this.externals.push({ object: routeWS });
callback(routeWS);
return this;
}
/**
* Internal Method for Generating Router Object
* @since 6.0.0
*/
async getData(prefix) {
if (!this.hasCalledGet)
for (const external of this.externals) {
const result = await external.object.getData(external.addPrefix ?? "/");
if ("routes" in result && result.routes.length > 0)
this.routes.push(...result.routes.map((r) => {
r.path.addPrefix(prefix);
return r;
}));
if ("webSockets" in result && result.webSockets.length > 0)
this.webSockets.push(...result.webSockets.map((r) => {
r.path.addPrefix(prefix);
return r;
}));
if ("defaultHeaders" in result)
this.parsedHeaders = Object.assign(this.parsedHeaders, result.defaultHeaders);
}
this.hasCalledGet = true;
return {
routes: this.routes,
webSockets: this.webSockets
};
}
}
export {
RouteFile as default
};