MicroRest Server
A minimal, but fully functional REST server for NodeJS.
Use for proof-of concepts, simple private servers and so on.
Install
npm i --save @rgwch/mikrorest
Use
see src/demo.ts. Run with npm run demo
or npx ts-node src/demo.ts
API
export type MikroRestHandler = (req: IncomingMessage, res: ServerResponse) => Promise<boolean>;
export interface MikroRestRoute {
method: MikroRestMethod;
path: string;
handlers: Array<MikroRestHandler>;
}
export type MikroRestOptions = {
port?: number;
allowedHeadersDevel?: string[];
allowedMethodsDevel?: string[];
allowedOriginsDevel?: string[];
allowedHeadersProd?: string[];
allowedMethodsProd?: string[];
allowedOriginsProd?: string[];
};
public constructor(options?:MikroRestOptions)
public addRoute(method: MikroRestMethod, path: string, ...handlers: Array<MikroRestHandler>)
public addStaticDir(dir: string)
public clearRoutes()
public start()
public readJsonBody(req: IncomingMessage, res?: ServerResponse): Promise<any>
public getUrl(req: IncomingMessage): URL {
return new URL(req.url!, `http://${req.headers.host}`);
}
public getParams(req: IncomingMessage): URLSearchParams {
return this.getUrl(req).searchParams;
}
public sendJson(res?: ServerResponse, body?: any, code: number = 200, headers?: { [key: string]: string })
public sendHtml(res?: ServerResponse, body?: string, code: number = 200, headers?: { [key: string]: string })
public sendPlain(res?: ServerResponse, text?: string, code: number = 200, headers?: { [key: string]: string })
public sendBuffer(res?: ServerResponse, buffer?: Buffer, code: number = 200, headers?: { [key: string]: string })
Tests
Tests were created by Github Copilot. See tests/README.md
Limitations
No path parameters, only query parameters. Things like http://localhost:3339/user/{name}/any?/load
will not work with mikrorest. Use http://localhost:3339/user/load?name=name&any=thing
instead.
Or use a full featured framework like Express.js or Koa.js.