Skip to content

Commit

Permalink
use get-ready to refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
fengmk2 committed Dec 18, 2024
1 parent 65c449a commit 2b433d0
Show file tree
Hide file tree
Showing 7 changed files with 246 additions and 316 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,7 @@ It can be overridden by child class, but should not be called directly. It must

- Drop `.awaitFirst(events)` support
- Drop generator function support
- Don't catch event listener inside error

### License

Expand Down
11 changes: 6 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@
"node": ">= 18.19.0"
},
"dependencies": {
"get-ready": "^3.3.0",
"gals": "^1.0.2",
"get-ready": "^3.4.0",
"is-type-of": "^2.2.0",
"utility": "^2.3.0"
},
Expand All @@ -32,17 +33,16 @@
"egg-bin": "6",
"eslint": "8",
"eslint-config-egg": "14",
"runscript": "^2.0.1",
"tshy": "3",
"tshy-after": "1",
"typescript": "5"
},
"scripts": {
"lint": "eslint --cache src test --ext .ts",
"pretest": "npm run lint -- --fix && npm run prepublishOnly",
"test": "egg-bin test",
"test": "egg-bin test -p --timeout 5000",
"preci": "npm run lint && npm run prepublishOnly && attw --pack",
"ci": "egg-bin cov",
"ci": "egg-bin cov -p",
"prepublishOnly": "tshy && tshy-after"
},
"type": "module",
Expand Down Expand Up @@ -70,5 +70,6 @@
"src"
],
"types": "./dist/commonjs/index.d.ts",
"main": "./dist/commonjs/index.js"
"main": "./dist/commonjs/index.js",
"module": "./dist/esm/index.js"
}
29 changes: 0 additions & 29 deletions src/index.d.ts

This file was deleted.

31 changes: 0 additions & 31 deletions src/index.test-d.ts

This file was deleted.

38 changes: 27 additions & 11 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import util from 'node:util';
import assert from 'node:assert';
import { once } from 'node:events';
import { AsyncLocalStorage } from 'node:async_hooks';
import { getAsyncLocalStorage } from 'gals';
import { ReadyEventEmitter } from 'get-ready';
import { isPromise, isGeneratorFunction } from 'is-type-of';
import { promiseTimeout } from 'utility';
Expand All @@ -12,28 +13,38 @@ export interface BaseOptions<T = any> {
[key: string]: any;
}

export class Base<T = any> extends ReadyEventEmitter {
export abstract class Base<T = any> extends ReadyEventEmitter {
options: BaseOptions<T>;
#closed = false;
#localStorage: AsyncLocalStorage<T>;

constructor(options?: BaseOptions<T>) {
super();

if (options?.initMethod) {
const initMethod = Reflect.get(this, options.initMethod);
const initMethod = Reflect.get(this, options.initMethod) as () => Promise<void>;
assert(typeof initMethod === 'function',
`[sdk-base] this.${options.initMethod} should be a function`);
assert(!isGeneratorFunction(initMethod),
`[sdk-base] this.${options.initMethod} generator function is not support`);
`[sdk-base] this.${options.initMethod} should not be generator function`);

process.nextTick(() => {
const ret = initMethod.apply(this);
assert(isPromise(ret), `[sdk-base] this.${options.initMethod} should return a promise`);
ret.then(() => this.ready(true))
.catch(err => this.ready(err));
ret.then(() => {
this.ready(true);
}).catch(err => {
const hasReadyCallbacks = this.hasReadyCallbacks;
this.ready(err);
// no ready callbacks, should emit error event instead
if (!hasReadyCallbacks) {
this.emit('error', err);
}
});
});
}
this.options = options ?? {};
this.#localStorage = this.options.localStorage ?? getAsyncLocalStorage<T>();
this.on('error', err => {
this._defaultErrorHandler(err);
});
Expand All @@ -42,16 +53,17 @@ export class Base<T = any> extends ReadyEventEmitter {
/**
* support `await this.await('event')`
*/
await(event: string) {
return once(this, event);
async await(event: string) {
const values = await once(this, event);
return values[0];
}

/**
* get AsyncLocalStorage from options
* @return {AsyncLocalStorage} asyncLocalStorage instance or undefined
*/
get localStorage() {
return this.options.localStorage;
return this.#localStorage;
}

async readyOrTimeout(milliseconds: number) {
Expand Down Expand Up @@ -87,15 +99,19 @@ export class Base<T = any> extends ReadyEventEmitter {
return;
}
this.#closed = true;
const closeFunc = Reflect.get(this, '_close');
if (typeof closeFunc !== 'function') {
const closeMethod = Reflect.get(this, '_close') as () => Promise<void>;
if (typeof closeMethod !== 'function') {
return;
}

try {
await closeFunc.apply(this);
await closeMethod.apply(this);
} catch (err) {
this.emit('error', err);
}
}

get isClosed() {
return this.#closed;
}
}
5 changes: 2 additions & 3 deletions test/fixtures/ts/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import Base, { BaseOptions } from '../../..';
import { Base, BaseOptions } from '../../../src/index.js';

class FooContext {
traceId?: string;
Expand Down Expand Up @@ -47,8 +47,7 @@ export async function test() {
console.log('localStorage should be undefined: %o', client.localStorage?.getStore());
});
await client.await('someEvent');
await client.awaitFirst([ 'one', 'two' ]);
// await client.awaitFirst([ 'one', 'two' ]);

return client.isReady;

}
Loading

0 comments on commit 2b433d0

Please sign in to comment.