import { Application$ } from "../app" ; import { readdir , pathExists } from "fs-extra" ; import * as path from "path" ; import { paths } from "../path" ; import { Container } from "typedi" ; import { getOutput } from "../utils" ; export interface Service$ { enable : boolean ; level : number ; init ( app ) : Promise < any > ; } export interface ServiceFactory$ { new ( ) : Service$ ; } export default class Service implements Service$ { public level : number = 0 ; public enable = true ; constructor ( ) { } async init ( ) { } } param s export function isValidService ( s ) { return s instanceof Service ; } /**
 * load service
 */ export async function loadService ( ) { const serviceFiles = ( ( await pathExists ( paths . service ) ) ? await readdir ( paths . service ) : [ ] ) . filter ( file => /\.service.t|jsx?$/ . test ( file ) ) ; const services = serviceFiles . map ( serviceFile => { const filePath = path . join ( paths . service , serviceFile ) ; const ServiceFactory = getOutput ( require ( filePath ) ) ; const service = < Service$ > Container . get ( ServiceFactory ) ; if ( ! isValidService ( service ) ) { throw new Error ( `The file ${ filePath } is not a service file.` ) ; } return service ; } ) . sort ( ( a ) => - a . level ) ; while ( services . length ) { const service = services . shift ( ) ; await service . init ( this ) ; } }