1
0
Fork 0

NodeCallback<T, R>: New type to simplify callback declarations

Just trying to reduce some boilerplate.  I kept this as a separate commit to
illustrate clearly how this type of things is done since we'll have people
learning TypeScript.

* src/types/misc.ts (NodeCallback<T,R>): New type.
* src/server/dapi/TokenedDataApi.ts: Use it.
* test/server/dapi/TokenedDataApiTest.ts: Use it.
master
Mike Gerwitz 2019-10-14 14:47:33 -04:00
parent 07c8b55475
commit d8c065817f
3 changed files with 19 additions and 9 deletions

View File

@ -79,7 +79,7 @@ export class TokenedDataApi implements DataApi
*/
request(
data: DataApiInput,
callback: ( e: Error | null, data: DataApiResult | null ) => void,
callback: NodeCallback<DataApiResult>,
id: string
): this
{
@ -144,7 +144,7 @@ export class TokenedDataApi implements DataApi
private _replyUnlessStale(
newtok: Token<TokenState.DONE>,
resp_data: DataApiResult,
callback: ( e: Error | null, data: DataApiResult | null ) => void,
callback: NodeCallback<DataApiResult>,
id: string
): void
{

10
src/types/misc.d.ts vendored
View File

@ -44,3 +44,13 @@ type NominalType<K, T> = K & { __nominal_type__: T };
* Number of seconds since the Unix epoch (1970-01-01 UTC).
*/
type UnixTimestamp = NominalType<number, 'UnixTimestamp'>;
/**
* Oldschool NodeJS callback
*
* We should migrate to promises over time. The purpose of this type is to
* reduce the boilerplate of these function definitions, and to clearly
* document that this pattern is something that used to be done frequently.
*/
type NodeCallback<T, R = void> = ( e: Error | null, result: T | null ) => R;

View File

@ -121,9 +121,9 @@ describe( 'TokenedDataApi', () =>
const mock_dapi = new class implements DataApi
{
request(
given_data: DataApiInput,
callback: ( e: Error|null, data: DataApiResult|null ) => void,
given_id: string
given_data: DataApiInput,
callback: NodeCallback<DataApiResult>,
given_id: string,
): this
{
expect( given_data ).to.equal( expected_data );
@ -141,7 +141,7 @@ describe( 'TokenedDataApi', () =>
return mock_tstore;
};
const callback = ( e: Error|null, data: DataApiResult|null ) =>
const callback: NodeCallback<DataApiResult> = ( e, data ) =>
{
expect( tok_completed ).to.be.true;
@ -197,8 +197,8 @@ describe( 'TokenedDataApi', () =>
const mock_dapi = new class implements DataApi
{
request(
_: any,
callback: ( e: Error|null, data: DataApiResult|null ) => void,
_: any,
callback: NodeCallback<DataApiResult>,
)
{
callback( expected_err, null );
@ -206,7 +206,7 @@ describe( 'TokenedDataApi', () =>
}
};
const callback = ( e: Error|null, data: DataApiResult|null ) =>
const callback: NodeCallback<DataApiResult> = ( e, data ) =>
{
expect( data ).to.equal( null );
expect( e ).to.equal( expected_err );