import { Service, ServiceMatcher } from "./service" import * as Leaf from "leaf-ts" import { ExpressService } from "../service/expressService" import * as express from "express" import * as urlModule from "url" import * as colors from "colors" import * as PathToRegExp from "path-to-regexp" let useColors = colors import { RouteDecorator } from "./decorator" export interface Request extends express.Request { } export interface Response extends express.Response { } export abstract class RouteService extends Service { public routes: RouteConstructor[] = [] public prefix: string = "/" constructor(public spec?: T, defaultSettings?: TSettings, settings?: TSettings) { super(defaultSettings || {} as any, settings || {} as any) } mergeSpec(spec: APIServiceSpec) { if (!this.spec) this.spec = {} as T for (let key in spec) { this.spec[key] = spec[key] } } readonly dependencies: ServiceMatcher[] = ["ExpressService"] services: { ExpressService: ExpressService } afterInitialize() { if (!this.isInstalled && this.services.ExpressService) { this.installTo(this.services.ExpressService.server) } } decorateAPI(name: K, dec: RouteDecorator) { for (let route of this.routes) { if (route.apiName == name) { route.decorate(dec) } } } addRoute(RouteConstructor) { this.routes.push(RouteConstructor) } decorateAll(...decs: RouteDecorator[]) { this.commonDecorateStacks.push(...decs) return this } clearDecorateAll() { this.commonDecorateStacks.length = 0 } private commonDecorateStacks = [] private decorateStacks = [] decorate(...decs: RouteDecorator[]) { this.decorateStacks.push(...decs) return this } api(name: K, ...callbacks: ((this: this["spec"][K] & APIRoute, context?: this["spec"][K] & APIRoute) => void)[]) { if (!this.spec) { throw new Error("No spec provided") } if (!this.spec[name]) { throw new Error("Unknown spec" + name) } let service = this let callback = callbacks.pop() let canonicalName = Leaf.Util.slugToCamel(this.name.toString().replace(/^api\./, "").replace(/\./, "-")) let Cons = class extends APIRoute{ static apiName = name as string constructor(arg) { super(arg) let decs = Cons.decorators this.decorate(...decs) } name = name as string path = service.spec[name].path || canonicalName + "/" + name as string method = service.spec[name].method || service.defaultMethod handle() { callback.call(this, this) } } Cons.decorators = [] Cons.decorators.push(...this.commonDecorateStacks) Cons.decorators.push(...this.decorateStacks.slice(0)) this.decorateStacks.length = 0 this.addRoute(Cons) return Cons as any as APIRoute & T[K] } public getAPI(name: K): APIRoute { return this.getRoute(name) as APIRoute } public getRoute(name: keyof T): Route { for (let Cons of this.routes) { let route = new Cons(this) if (route.name == name) return route } return null } public defaultMethod: METHOD_ENUM = "POST" public isInstalled = false installTo(server: express.Application) { if (!server) return this.isInstalled = true for (let cons of this.routes) { let route = new cons(this) if (!route.path) continue if (route instanceof MiddlewareRoute) { let handler = (req, res, next) => { let route = new cons(this) route.services = this.services route.handleRawRequest(req, res, next) } if (route.path) { server.use(route.path, handler) } else { server.use(handler) } console.log(`Install middleware ${useColors.yellow(cons.name)}`) continue } let path = urlModule.resolve(this.prefix, route.path) let method = route.method.toLowerCase() if (route.name) { console.log(`${useColors.yellow(route.method)} => ${useColors.yellow(path)} ~ Install ${useColors.yellow(route.name)}`) } else { console.log(`Install ${useColors.yellow(route.method)} => ${useColors.yellow(path)} `) } server[method](path, (req, res, next) => { let route = new cons(this) route.services = this.services route.handleRawRequest(req, res, next) }) } } addRoutes(...obj: any[]) { for (let item of obj) { if (this.isRouteConstructor(item)) { this.addRoute(item) } else { for (let name in item) { let target = item[name] if (this.isRouteConstructor(target)) { this.addRoute(target) } } } } } isRouteConstructor(obj) { return obj && obj.prototype && obj.prototype["thisObjectIsTruelyARoute"] == "thisObjectIsTruelyARoute" } } export abstract class RouteServiceTemplate extends RouteService{ name: string constructor(spec: { API: T prefix?: string name: string }) { super(spec.API) this.name = spec.name this.prefix = spec.prefix || "" } } export interface RouteConstructor { new(service?: RouteService): Route apiName: string decorate(...decs: RouteDecorator[]) } export abstract class Route { static decorate(fn: RouteDecorator) { this.decorators.push(fn) return this } static decorators: RouteDecorator[] = [] constructor(public service: TService) { if (!this["handle"]) { this["handle"] = () => { this.res.json({ state: false, error: new Error("Not implemented"), data: "Not implemented" }); } } } decorate(...decs: RouteDecorator[]) { let dec: RouteDecorator decs = decs.slice() while (dec = decs.pop()) { let des: { value? } = { value: this.handle } dec(this, "handle", des) if (des.value != this.handle) { this.handle = des.value } } } name: string mime: TMIME abstract path: string method: METHOD_ENUM = "GET" params = {} body = {} info = {} services: TService["services"] query = {} next: Function req: Request res: Response handleRawRequest(req, res, next) { if (!req._routeInfo) { req._routeInfo = {} } this.req = req this.res = res this.info = req._routeInfo this.next = next this.body = req.body || {} this.params = req.params || {} this.query = req.query || {} this.handle() } end(content: any) { this.res.contentType(this.mime) this.res.end(content) } abstract handle(); notFound(content?: string, mime?: TMIME) { this.mime = mime || "text/plaintext" as TMIME this.res.statusCode = 404 this.res.end(content || "404") } } Route.prototype["thisObjectIsTruelyARoute"] = "thisObjectIsTruelyARoute" export abstract class DynamicResourceRoute extends Route{ } export abstract class MiddlewareRoute extends Route{ path = null method: Method.ALL mock(url: string, data: { [name: string]: any }, callback: (err?: any) => void) { for (let name in data) { this[name] = data[name] } let keys = [] if (this.path) { let reg = PathToRegExp(this.path, keys, {}) let match = reg.exec(url) if (!match) { callback(new Error(`${url} doesn't match ${this.path}`)) return } let params = {} for (let i = 0; i < keys.length; i++) { let k = keys[i] params[k.name] = match[i + 1] } this.params = params if (!reg.test(url)) { callback(new Error("Url not match")) return } } this.next = () => { callback() } this.handle() } } export abstract class PageRoute extends Route<"text/html">{ method: Method.GET readonly mime = "text/html" html(content: string) { this.end(content) } } export abstract class APIRoute extends Route<"application/json", TService> { static apiName = "null" constructor(service: TService) { super(service) this.done = this.done.bind(this) this.error = this.error.bind(this) this.success = this.success.bind(this) this.ok = this.success } done(err: TError, result: TResponse) { if (err) { this.error(err) } else { this.success(result) } } ok(data: TResponse) { return this.success(data) } success(data: TResponse) { if (this._success) { this._success(data) return } this.json({ state: true, data }) } error(err: TError) { if (this._error) { this._error(err) return } this.json({ state: false, error: err }) } // for mockup _error: (err: TError) => void _success: (data: any) => void json(data) { if (data && data.error instanceof Error) { data.error = { name: data.error.name || "UnknownError", message: data.error.message || null, stack: data.error.stack, via: data.error.via || null } } this.res.json(data) } mock(url: string, data: { [name: string]: any }, callback: (err?: TError, data?: TResponse) => void) { for (let name in data) { this[name] = data[name] } let keys = [] let reg = PathToRegExp(this.path, keys, {}) let match = reg.exec(url) if (!match) { callback(new Error(`${url} doesn't match ${this.path}`) as TError) return } let params = {} for (let i = 0; i < keys.length; i++) { let k = keys[i] params[k.name] = match[i + 1] } this.params = params if (!reg.test(url)) { callback(new Error("Url not match") as TError) return } let returnError: Error = null let returnValue: TResponse = null this._error = (err) => { clear() callback(err, null) } this._success = (data) => { clear() callback(null, data) } let clear = () => { this._error = null this._success = null } this.handle() } } export type MIME = "text/html" | "text/javascript" | "text/json" | "application/json" | "application/octet-stream" | string export type METHOD_ENUM = "GET" | "POST" | "DELETE" | "PUT" | "ALL" export type Method = string & T export namespace Method { export const GET: Method<"GET"> = "GET" export const POST: Method<"POST"> = "POST" export const DELETE: Method<"DELETE"> = "DELETE" export const PUT: Method<"PUT"> = "PUT" export const ALL: Method<"ALL"> = "ALL" export type POST = Method<"POST"> export type GET = Method<"GET"> export type DELETE = Method<"DELETE"> export type PUT = Method<"PUT"> export type ALL = Method<"ALL"> } // legacy export type APITemplate = APISpec export interface APISpec { path?: string method?: METHOD_ENUM return?: any error?: Error service?: RouteService } export type APIServiceSpec = { [name: string]: APISpec } export abstract class APIBase implements APITemplate { abstract path: string return: any error: Error method?: METHOD_ENUM }