ソースを参照

Adds new serialize decorator

main
Eric Amodio 3年前
コミット
9a9b9ce870
3個のファイルの変更65行の追加3行の削除
  1. +1
    -0
      src/system.ts
  2. +3
    -3
      src/system/decorators/gate.ts
  3. +61
    -0
      src/system/decorators/serialize.ts

+ 1
- 0
src/system.ts ファイルの表示

@ -23,6 +23,7 @@ export * as Dates from './system/date';
export * from './system/decorators/gate';
export * from './system/decorators/log';
export * from './system/decorators/memoize';
export * from './system/decorators/serialize';
export * from './system/decorators/timeout';
export * as Encoding from './system/encoding';
export * as Functions from './system/function';

+ 3
- 3
src/system/decorators/gate.ts ファイルの表示

@ -1,4 +1,5 @@
'use strict';
import { Uri } from 'vscode';
import { is as isPromise } from '../promise';
const emptyStr = '';
@ -8,9 +9,8 @@ function defaultResolver(...args: any[]): string {
const arg0 = args[0];
if (arg0 == null) return emptyStr;
if (typeof arg0 === 'string') return arg0;
if (typeof arg0 === 'number' || typeof arg0 === 'boolean') {
return String(arg0);
}
if (typeof arg0 === 'number' || typeof arg0 === 'boolean' || arg0 instanceof Error) return String(arg0);
if (arg0 instanceof Uri) return arg0.toString();
return JSON.stringify(arg0);
}

+ 61
- 0
src/system/decorators/serialize.ts ファイルの表示

@ -0,0 +1,61 @@
'use strict';
import { Uri } from 'vscode';
const emptyStr = '';
function defaultResolver(...args: any[]): string {
if (args.length === 1) {
const arg0 = args[0];
if (arg0 === undefined) return emptyStr;
if (typeof arg0 === 'string') return arg0;
if (typeof arg0 === 'number' || typeof arg0 === 'boolean' || arg0 instanceof Error) return String(arg0);
if (arg0 instanceof Uri) return arg0.toString();
return JSON.stringify(arg0);
}
return JSON.stringify(args);
}
export function serialize<T extends (...arg: any) => any>(
resolver?: (...args: Parameters<T>) => string,
): (target: any, key: string, descriptor: PropertyDescriptor) => void {
return (target: any, key: string, descriptor: PropertyDescriptor) => {
let fn: Function | undefined;
if (typeof descriptor.value === 'function') {
fn = descriptor.value;
} else if (typeof descriptor.get === 'function') {
fn = descriptor.get;
}
if (fn === undefined) throw new Error('Not supported');
const serializeKey = `$serialize$${key}`;
descriptor.value = function (this: any, ...args: any[]) {
const prop =
args.length === 0
? serializeKey
: `${serializeKey}$${(resolver ?? defaultResolver)(...(args as Parameters<T>))}`;
if (!Object.prototype.hasOwnProperty.call(this, prop)) {
Object.defineProperty(this, prop, {
configurable: false,
enumerable: false,
writable: true,
value: undefined,
});
}
let promise = this[prop];
const run = () => fn!.apply(this, args);
if (promise === undefined) {
promise = run();
} else {
promise = promise.then(run, run);
}
this[prop] = promise;
return promise;
};
};
}

読み込み中…
キャンセル
保存