前言

最近公司局部前端工程转 typeScript 的实际中,也尝试了 ts 的写法,诸如依赖注入、管制翻转、注解等。这些概念在 Java 等后端开发中利用可能更为宽泛,但也不影响在前端畛域的尝鲜。最终的写法如下;

依赖注入:

export default class DataQuery extends VueComponent {    @Inject('baseWebDataService')    public baseWebDataService!: BaseWebDataService;    @Inject('stationUtilService')    public stationUtilService!: StationUtilService;    @Inject('configService')    public configService!: ConfigService;}

网络申请:

export default class DataQuery extends VueComponent {    /**     * 获取根底信息     * @param params     * @param res     * @protected     */    @HttpGet('/basicinfo/tree')    @HttpHeader(['Content-Type: application/json'])    @HttpBaseUrl('http://127.0.0.1')    protected async getBasicStationTreeData(@HttpParams() params: BasicStationForm, @HttpRes() res?: any) {        // 在此处能够有本人的业务数据处理逻辑        const queryKey: string = this.buildTempKeyByUrl(params);        if (Array.isArray(res.data) && res.data.length) {            RESOURCE_STATION_TREE_DATA.set(queryKey, res.data);        }        return res.data;    }}

明天的文章中来分享一下如何基于注解(装璜器)的形式来编写网络申请层,其中的代码已提交到
源码
感兴趣的同学能够参考参考。

基于代码也打包了 npm 插件 @canyuegongzi/decorator-http-template

插件应用

前置常识

装璜器

装璜器(Decorator)是一种与类(class)相干的语法,用来正文或批改类和类办法。许多面向对象的语言都有这项性能。

javaScript 对于元编程的反对尚不如 ts 欠缺,因而以 typeScript 来开发此插件。

ts 中装璜器大抵分为类装璜器、属性装璜器、办法装璜器、参数装璜器。

类装璜器

此类装璜器能够是一般装璜器(无奈传参)也能够是工厂模式(能够传参),工厂模式甚至能够间接重载整个类,ts 中的类型束缚如下。

declare type ClassDecorator = <TFunction extends Function>(target: TFunction) => TFunction | void;

一般装璜器:

此注解中 target 为 被润饰的类,在此能够扩大被润饰的类。

function log<T extends any>(target: T){    // console.log(target)}@logclass Test {}

工厂模式

此类注解返回函数,能够通柯里化的形式传递参数。

function log(params: any){    return function<T extends any> (target: T) {}}@log('/login')class Test {}

属性装璜器

此类装璜器能够润饰类的成员属性,模式如类装璜器一样既能够是传统模式也能够采纳工厂模式,此种装璜器在依赖注入中有大量的利用,ts 中的类型束缚如下。

declare type PropertyDecorator = (target: Object, propertyKey: string | symbol) => void;
export function Inject(id?: string): PropertyDecorator {    return (target: Record<string, any>, propertyKey: string | symbol) => {        // 在此出能够实现与依赖注入相干的逻辑    };}class Test {    @Inject('configService')    public configService!: ConfigService;}

办法装璜器

此类装璜器能够重载类的成员函数,后续内容中会大量应用此类装璜器,此类装璜器存在三个参数,其一: target 为被润饰的类,其二:propertyKey是被润饰的成员函数的函数名,其三 descriptor 是被润饰的成员函数,在通常状况下能够通过 descriptor 参数重载此办法。 ts 中的类型束缚如下。

declare type MethodDecorator = <T>(target: Object, propertyKey: string | symbol, descriptor: TypedPropertyDescriptor<T>) => TypedPropertyDescriptor<T> | void;

以下代码实现一个简略的接口缓存装璜器。

const ExpriesMemoryCache = new Map();export function ApiCache(timeout = 120, keyArray = [],): MethodDecorator {    return (target, name, descriptor) => {        // 获取被润饰成员函数的原值        const originalMethod = descriptor.value;        // 重载此函数        descriptor.value = async function (...args) {            const argumentsArr = Array.from(arguments).concat(keyArray);            let key = JSON.stringify(name, Array.from(new Set(argumentsArr)));            let promise = ExpriesMemoryCache.get(key);            if (!promise) {                // 缓存中没有该接口的缓存数据时通过originalMethod.apply 形式调用原函数申请数据                promise = await originalMethod.apply(null, arguments).catch(async error => {                    ExpriesMemoryCache.delete(key)                    return Promise.reject(error);                });                // 数据申请实现后将数据存入缓存,下一次调用该形式时间接从缓存中获取数据                ExpriesMemoryCache.set(key, promise)            }            return promise;        };        return descriptor;    }}class Test {    @ApiCache(120, [])    public getData() {            }}

以上代码实现了一个简易版的接口缓存注解,实现较为简陋,做的好的话能够持续扩大此函数,实现诸如定时缓存、竞速缓存等性能。

参数装璜器

此类装璜器次要用来注解类成员函数中参数,该装璜器有存在参数,其一:target 为 被润饰函数的所属类,其二:propertyKey 为被润饰的函数名,其三:parameterIndex 为参数的索引(第几个参数),该中装璜器在服务端开发中有大量的利用,如 Controller 层中查问参数的利用,ts 类型束缚如下。

declare type ParameterDecorator = (target: Object, propertyKey: string | symbol, parameterIndex: number) => void;
class Test {  getInfo(@paramDecorator name: string, age: number) {    console.log(name, age);  }}function paramDecorator(target: any, method: string, paramIndex: number) {    // target 为 Test 类    // method 为 'getInfo'    // paramIndex 为 0 被润饰的参数的参数索引    console.log(target, method, paramIndex);}

reflect-metadata

Reflect Metadata 是 ES7 的一个提案,它次要用来在申明的时候增加和读取元数据。TypeScript 在 1.5+ 的版本曾经反对它,你只须要:

  1. npm i reflect-metadata --save 并在入口文件中 import 'reflect-metadata'
  2. 在 tsconfig.json 里配置 emitDecoratorMetadata 选项

defineMetadata

当作 Decorator 应用,当润饰类时,在类上增加元数据,当润饰类属性时,在类原型的属性上增加元数据。

Reflect.defineMetadata(ReqMethodQuery, parameterIndex, target, propertyKey);

getMetadata

该 Api 用于获取target的元数据值, 会往原型链上找。

hasOwnMetadata

跟Object.prototype.hasOwnProperty相似, 是只查找对象上的元数据, 而不会持续向上查找原型链上的,如:

const reqQueryIndex: number = Reflect.getOwnMetadata(ReqMethodQuery, target, propertyKey);

其余

对于 reflect-metadata 的概念在此处不作具体应用介绍,不过找了几篇文章,能够参考下:

  1. 掘金1
  2. reflect-metadata
  3. github

开始

有之前的前置常识后,当初能够正式开始插件了。

网络申请办法装璜器

通过装璜器形式编写网络申请层。同样须要实现 Get、Post、Delete、Patch。

此处只以 Post、Get 为例,外围办法 createHttpDecoratorFunction 在下一步实现。

/** * post post申请 * @param url<string> 接口地址   /user/login * @param data<Object> 申请参数 个别参数都是动静参数,不会采纳这中形式 * @param options<string[] | string> 申请头部参数 倡议间接应用HttpHeader 注解 * @constructor */export function HttpPost(url: string, data?: any, options: string[] = []) {    return createHttpDecoratorFunction('POST', url, data, options)}/** * post get申请  /user/list | /user/usrInfo/:id * @param url<string> 接口地址 * @param data<Object> 申请参数 个别参数都是动静参数,不会采纳这中形式 * @param options<string[] | string> 申请头部参数 倡议间接应用HttpHeader 注解 * @constructor */export function HttpGet(url: string, data?: any, options: string[] = []) {    return createHttpDecoratorFunction('GET', url, data, options)}

网络查问参数装璜器

通过此类型装璜器能够实现网络申请的参数传递,成果如下:能够通过 HttpParams、HttpQuery、HttpPostData 来设置网络申请的参数。

class Test {    /**     * 获取数据查问     * @protected     */    @HttpGet('/data-search/list')    @HttpHeader(['Content-Type: application/json'])    protected async getDataList(@HttpParams() queryDataParams: QueryDataParams, @HttpRes() res?: any) {}   }

HttpParams 和 HttpPostData 能够定义须要传递的参数,其实现形式参考了 nest 的应用形式,既能够将整个实体当作参数传递给后端接口,也能够通过对象字段标识只传递对象的一个属性。
当通过此类装璜器装璜的成员函数,在代码编译阶段会先通过 Reflect.defineMetadata 绑定参数索引。不便在后续的函数调用中获取参数,也能够通过柯里化的形式保留参数供后续应用。
此出代码只以 HttpParams 为例,其余 HttpPostData、HttpQuery 都是同样的情理,代码能够参考源码。

/** * 申请参数注解   @HttpParams()  | @HttpParams('id') * @param key 参数key,当存在此参数时,申请参数中只会蕴含此key的值, 大部分状况下实用于 user/:id  类接口, 默认发送全副参数 * @constructor */export function HttpParams(key?: string) {    return function (target: any, propertyKey: string | symbol, parameterIndex: number) {        // 通过 Reflect.defineMetadata 定义元数据        Reflect.defineMetadata(ReqMethodParams, parameterIndex, target, propertyKey);        // 装璜器存在参数时 须要非凡绑定元数据        if (key) {            Reflect.defineMetadata(ReqMethodKeyParams, key, target, propertyKey);        }    }}

HttpRes装璜器

HttpRes 装璜器的核心作用是标识能够通过该参数能够拿到后端返回的数据。还是以之前的案例,getDataList 的第二个参数通过 HttpRes 润饰,在函数体外部就能够通过 res 获取后端返回的数据。

class Test {    /**     * 获取数据查问     * @protected     */    @HttpGet('/data-search/list')    @HttpHeader(['Content-Type: application/json'])    protected async getDataList(@HttpParams() queryDataParams: QueryDataParams, @HttpRes() res?: any) {        // 通过 res 能够拿到后端返回的Reponse, 不过这个 res 是 AxiosResponse 类型,默认状况下,函数体为空时。函数会返回该res.        console.log(res.data);    }   }

HttpHeader装璜器

HttpHeader 装璜器能够增加网络申请的头部参数,其参数既能够是字符类型也能够是字符汇合。

/** * 申请头部 * @param headers<string[] | string> * @constructor */export function HttpHeader(headers: string | string[]) {    return headerDecoratorFactory(headers);}function headerDecoratorFactory(headers: string | string[]) {    return function (target: any, propertyKey: string) {        const headersConfig: string[] = typeof headers === 'string'? [headers]: headers;        Reflect.defineMetadata(ReqMethodHeaders, headersConfig, target, propertyKey);    }}

HttpBaseUrl装璜器

HttpBaseUrl 装璜器能够设置网络申请的前缀。

/** * 接口前缀地址 * @param baseUrl<string> 接口地址 * @constructor */export function HttpBaseUrl(baseUrl: string) {    return function (target: any, propertyKey: string) {        Reflect.defineMetadata(ReqHttpBaseUrl, baseUrl, target, propertyKey);    }}

createHttpDecoratorFunction

该办法是实现装璜器数据拜访的外围办法,大略步骤也较为简单,重载被润饰的函数能够实现其性能:

1: 通过 getOwnMetadata 获取定义的元数据;
2: 调用 axios 实现网络申请;
3: 判断函数体是否为空,为空的申请下间接返回 Response,当存在函数体时会先用 apply 调用函数体,而后再完结掉函数。

/** * 创立申请装璜器 * @param type<HttpTemplateMethod> 申请类型 * @param url<String> 申请url * @param data<Object> 申请参数 * @param options<Object> 配置 */export const createHttpDecoratorFunction = (type: HttpTemplateMethod, url: string, data: any = {}, options: string[] = []) => {    return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {        // 保留原办法的值,不便后续步骤通过 apply 调用函数        const method: any = descriptor.value;        descriptor.value = async function () {            // 获取之前通过一系列注解定义的元数据,包含申请参数,baseUrl 等等            const { reqDataKey, reqParamsKey, responseType, reqQueryKey, baseUrl, reqHttpTransform, requestConfig,reqParamsIndex,reqQueryIndex,resIndex,reqDataIndex } = getMetadata(target, propertyKey)            try {                const args: Array<any> = [...arguments]                let query: any = {};                let params: any = {};                let postData: any = {};                let httpUrl = url;                // 当存在 HttpQuery 注解时 会拿到被 HttpQuery 注解的参数, 拿到 httpBaseUrl                // path 参数                if (reqQueryIndex >= 0) {                  const dataObj = getHttpData(type, httpUrl, args[reqQueryIndex], reqQueryKey);                  query = dataObj.data;                  httpUrl = dataObj.httpUrl;                }                // 当存在 HttpParams 注解时 会拿到被 HttpParams 注解的参数 拿到 httpBaseUrl                if (reqParamsIndex >= 0) {                    const dataObj = getHttpData(type, httpUrl, args[reqParamsIndex], reqParamsKey);                    params = dataObj.data;                    httpUrl = dataObj.httpUrl;                }                // post data数据                if (reqDataIndex >= 0) {                    const dataObj=  getHttpData(type, httpUrl, args[reqDataIndex], reqDataKey);                    httpUrl = dataObj.httpUrl;                    postData = dataObj.data                }                // 解决申请 headers                 const requestHttpConfig: any = [...requestConfig, ...options]                const res: any = await requestData(type, baseUrl ? baseUrl + httpUrl: httpUrl, { query, params, postData}, requestHttpConfig, reqHttpTransform, responseType)                // 判断函数体是否为空                if (isEmptyFunction(method) || resIndex === undefined || resIndex < 0) {                    return res;                }                // 解决参数 把 HttpRes 注解的参数间接替换为 后端返回的数据, 供 apply 调用                if (resIndex >= 0) args.splice(resIndex, 1, res)                return method.apply(this, args)            } catch (error) {                console.warn(error);                throw error            }        }    }}

getMetadata 办法较简略,间接获取一些列的元数据,当然也有更加简略的办法。

/** * 获取自定义数据配置 * @param target * @param propertyKey * */function getMetadata(target: any, propertyKey: string ) {    const resIndex: number = Reflect.getOwnMetadata(ResMethodKey, target, propertyKey);    const reqQueryIndex: number = Reflect.getOwnMetadata(ReqMethodQuery, target, propertyKey);    const reqParamsIndex: number = Reflect.getOwnMetadata(ReqMethodParams, target, propertyKey);    const reqDataIndex: number = Reflect.getOwnMetadata(ReqMethodData, target, propertyKey);    const reqDataKey: string = Reflect.getOwnMetadata(ReqMethodKeyData, target, propertyKey);    const reqParamsKey: string = Reflect.getOwnMetadata(ReqMethodKeyParams, target, propertyKey);    const reqQueryKey: string = Reflect.getOwnMetadata(ReqMethodKeyQuery, target, propertyKey);    const reqHttpTransform: number = Reflect.getOwnMetadata(ReqHttpTransformRequest, target, propertyKey);    const baseUrl: string = Reflect.getOwnMetadata(ReqHttpBaseUrl, target, propertyKey);    const responseType: ResponseType = Reflect.getOwnMetadata(ResHttpResponseType, target, propertyKey);    const requestConfig: string[] = Reflect.getOwnMetadata(ReqMethodHeaders, target, propertyKey) || [];    return { reqDataKey, reqParamsKey, responseType, reqQueryKey, baseUrl, reqHttpTransform, requestConfig,reqParamsIndex,reqQueryIndex,resIndex,reqDataIndex}}

requestData 办法和一般的网络申请无差别,实现如下:

/** * http 申请实体 * @param type * @param url * @param data * @param options * @param reqHttpTransform * @param responseType */export function requestData(type, url, data, options, reqHttpTransform, responseType) {    return new Promise(async (resolve, reject) => {        const { query, params, postData } = data;        const config: any = getConfig(options);        const requestData: any = {            url: url,            method: type,            headers: config,            params: params,            data: postData,            responseType: responseType || 'json'        }        // 存在数据转换器时,会在网络申请前调用该转换器        if (reqHttpTransform) {            reqHttpTransform['transformRequest'] = reqHttpTransform;        }        httpInstance.request(requestData).then((res: AxiosResponse) => {            resolve(res);        }).catch(e => {            reject(e);        })    })}

备注

  1. web 和 node 端能够采纳同样的形式申请数据;
  2. 装璜器只能装璜类或者类成员亦或者是类成员函数的参数。

最初

最初贴一下源码 源码
文章篇幅无限,不能对实现的每一个注解进行解说,感兴趣的同学能够先下载插件感触感触。也欢送各位在评论区一起探讨其余的实现形式。