UNPKG

@alwatr/nano-server

Version:

Elegant powerful nodejs server for nanoservice use cases, written in tiny TypeScript module.

179 lines 6.01 kB
/// <reference path="type.d.ts" /> /// <reference types="node" /> /// <reference types="node" /> /// <reference types="node" /> /// <reference types="node/http.js" /> import { type AlwatrLogger } from '@alwatr/logger'; import type { NanoServerConfig, ConnectionConfig } from './type.js'; import type { AlwatrServiceResponse, AlwatrServiceResponseFailed, AlwatrServiceResponseSuccess, AlwatrServiceResponseSuccessWithMeta, MaybePromise, Methods, ParamKeyType, ParamValueType, QueryParameters, Stringifyable, StringifyableRecord, UserAuth } from '@alwatr/type'; import type { IncomingMessage, ServerResponse } from 'node:http'; import type { Duplex } from 'node:stream'; export type RouteMiddleware<TData extends Stringifyable = Stringifyable, TMeta extends StringifyableRecord = StringifyableRecord> = (connection: AlwatrConnection) => MaybePromise<AlwatrServiceResponse<TData, TMeta> | null>; export type { NanoServerConfig, ConnectionConfig, AlwatrServiceResponse, AlwatrServiceResponseFailed, AlwatrServiceResponseSuccess, AlwatrServiceResponseSuccessWithMeta, }; export declare class AlwatrNanoServer { protected _config: NanoServerConfig; protected _logger: AlwatrLogger; /** * Core HTTP Server. */ httpServer: import("http").Server<typeof IncomingMessage, typeof ServerResponse>; /** * Create a server for nanoservice use cases. * * Example: * * ```ts * import {AlwatrNanoServer} from '@alwatr/nano-server'; * const nanoServer = new AlwatrNanoServer(); * * nanoServer.route('GET', '/', async (connection) => { * ok: true, * data: { * app: 'Alwatr Nanoservice Starter Kit', * message: 'Hello ;)', * }, * }; * ); * ``` */ constructor(config?: Partial<NanoServerConfig>); /** * Stops the HTTP server from accepting new connections. * * Example: * * ```ts * nanoserver.close(); * ``` */ close(): void; /** * Refers to how an application’s endpoints (URIs) respond to client requests. * * @param method - Acceptable methods. * @param route - Acceptable request path. * @param middleware - Request handler. * * Example: * * ```ts * nanoServer.route('GET', '/', async (connection) => { * return { * ok: true, * data: { * app: 'Alwatr Nanoservice Starter Kit', * message: 'Hello ;)', * }, * }); * }; * ``` */ route<TData extends Stringifyable = Stringifyable, TMeta extends StringifyableRecord = StringifyableRecord>(method: 'ALL' | Methods, route: 'all' | `/${string}`, middleware: RouteMiddleware<TData, TMeta>): void; /** * Responds to the request. * * Example: * ```ts * nanoServer.route('GET', '/', async (connection) => { * return { * ok: true, * data: { * app: 'Alwatr Nanoservice Starter Kit', * message: 'Hello ;)', * }, * }; * }); * ``` */ reply(serverResponse: ServerResponse, content: AlwatrServiceResponse<Stringifyable, StringifyableRecord>): void; protected _errorListener(err: NodeJS.ErrnoException): void; protected _clientErrorListener(err: NodeJS.ErrnoException, socket: Duplex): void; protected _onHealthCheckRequest(connection: AlwatrConnection): null; protected _onHOptionRequest(connection: AlwatrConnection): null; protected middlewareList: Record<string, Record<string, RouteMiddleware>>; protected _requestListener(incomingMessage: IncomingMessage, serverResponse: ServerResponse): Promise<void>; protected _notFoundListener: (connection: AlwatrConnection) => AlwatrServiceResponseFailed; } /** * Alwatr Connection */ export declare class AlwatrConnection { incomingMessage: IncomingMessage; serverResponse: ServerResponse; protected _config: ConnectionConfig; static _versionPattern: RegExp; /** * Request URL. */ readonly url: URL; /** * Request method. */ readonly method: Methods; protected _logger: AlwatrLogger; constructor(incomingMessage: IncomingMessage, serverResponse: ServerResponse, _config: ConnectionConfig); /** * Get the token placed in the request header. */ getAuthBearer(): string | null; /** * Get request body for POST, PUT and POST methods. * * Example: * ```ts * const body = await connection.getBody(); * ``` */ getBody(): Promise<string | null>; /** * Parse request body. * * @returns Request body. * * Example: * ```ts * const bodyData = await connection.requireJsonBody(); * ``` */ requireJsonBody<T extends StringifyableRecord>(): Promise<T>; /** * Parse and validate request token. * * @returns Request token. * * Example: * ```ts * const token = connection.requireToken((token) => token.length > 12); * if (token == null) return; * ``` */ requireToken(validator?: ((token: string) => boolean) | string[] | string): string; /** * Parse and get request user auth (include id and token). * * Example: * ```ts * const userAuth = connection.requireUserAuth(); * ``` */ getUserAuth(): UserAuth | null; /** * Parse query param and validate with param type. */ protected _sanitizeParam(name: string, type: ParamKeyType): ParamValueType | null; /** * Parse and validate query params. * * @returns Query params object. * * Example: * ```ts * const params = connection.requireQueryParams<{id: string}>({id: 'string'}); * console.log(params.id); * ``` */ requireQueryParams<T extends QueryParameters = QueryParameters>(params: Record<string, ParamKeyType>): T; getRemoteAddress(): string; requireClientId(): string; } //# sourceMappingURL=nano-server.d.ts.map