Skip to content
This repository was archived by the owner on May 8, 2020. It is now read-only.

Commit c8d3b51

Browse files
committed
refactor(async/await): Refactored most runtime promises to async/await pattern
1 parent 087a674 commit c8d3b51

File tree

7 files changed

+87
-96
lines changed

7 files changed

+87
-96
lines changed

src/common/stores/mock.store.ts

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -59,11 +59,12 @@ export abstract class MockStore<T extends AbstractModel> extends AbstractStore<T
5959
/**
6060
* @inheritdoc
6161
*/
62-
public findOne(id?: identifier): Promise<T> {
62+
public async findOne(id?: identifier): Promise<T> {
63+
6364
try {
64-
return Promise.resolve(this.modelCollection.findById(id));
65-
} catch (e){
66-
return this.saveOne(this.getMock(id))
65+
return await this.modelCollection.findById(id);
66+
} catch (e) {
67+
return await this.saveOne(this.getMock(id));
6768
}
6869
}
6970

src/common/stores/store.ts

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -81,15 +81,13 @@ export abstract class AbstractStore<T extends AbstractModel> {
8181
* @param validatorOptions
8282
* @returns {Promise<T>}
8383
*/
84-
public validate(model: T, validatorOptions?: ValidatorOptions): Promise<T> | never {
85-
86-
return this.validator.validate(model, validatorOptions)
87-
.then((errors: ValidationError[]) => {
88-
if (errors.length) {
89-
throw new ValidationException(null, errors)
90-
}
91-
return model;
92-
});
84+
public async validate(model: T, validatorOptions?: ValidatorOptions): Promise<T> | never {
85+
86+
const errors: ValidationError[] = await this.validator.validate(model, validatorOptions);
87+
if (errors.length) {
88+
throw new ValidationException(null, errors)
89+
}
90+
return model;
9391
}
9492

9593
/**

src/server/controllers/request.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ export class Request {
7070
* Extract the passed body object from the raw request
7171
* @returns {Promise<T>}
7272
*/
73-
public getPayload(): Promise<any> {
73+
public getPayload<T>(): Promise<T> {
7474
return new Promise((resolve, reject) => {
7575
this.raw.setEncoding('utf8');
7676

src/server/controllers/resource.controller.ts

Lines changed: 25 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -32,12 +32,9 @@ export abstract class ResourceController<M extends AbstractModel> extends Abstra
3232
* @returns {any}
3333
*/
3434
@Route('GET', '/:id')
35-
public getOne(request: Request, response: Response): Promise<Response> {
36-
37-
return this.modelStore
38-
.findOne(request.params()
39-
.get('id'))
40-
.then((model: M) => response.data(model));
35+
public async getOne(request: Request, response: Response): Promise<Response> {
36+
const model: M = await this.modelStore.findOne(request.params().get('id'));
37+
return response.data(model);
4138
}
4239

4340
/**
@@ -47,11 +44,9 @@ export abstract class ResourceController<M extends AbstractModel> extends Abstra
4744
* @returns {any}
4845
*/
4946
@Route('GET', '/')
50-
public getMany(request: Request, response: Response): Promise<Response> {
51-
52-
return this.modelStore
53-
.findMany()
54-
.then((collection: Collection<M>) => response.data(collection));
47+
public async getMany(request: Request, response: Response): Promise<Response> {
48+
const collection: Collection<M> = await this.modelStore.findMany();
49+
return response.data(collection);
5550
}
5651

5752
/**
@@ -85,12 +80,11 @@ export abstract class ResourceController<M extends AbstractModel> extends Abstra
8580
* @returns {Promise<Response>}
8681
*/
8782
@Route('DELETE', '/:id')
88-
public deleteOne(request: Request, response: Response): Promise<Response> {
83+
public async deleteOne(request: Request, response: Response): Promise<Response> {
8984

90-
return request.getPayload()
91-
.then((data: any) => this.modelStore.hydrate(data))
92-
.then((model: M) => this.modelStore.deleteOne(model))
93-
.then((model: M) => response.data(model));
85+
const model: M = await this.modelStore.hydrate(await request.getPayload());
86+
await this.modelStore.deleteOne(model);
87+
return response.data(model);
9488
}
9589

9690
/**
@@ -101,28 +95,25 @@ export abstract class ResourceController<M extends AbstractModel> extends Abstra
10195
* @param checkExists
10296
* @returns {Promise<Response>}
10397
*/
104-
protected savePayload(request: Request, response: Response, checkExists: boolean = false, validatorOptions: ValidatorOptions = {}): Promise<Response> {
105-
let modelPayload = request.getPayload()
106-
.then((data: any) => this.modelStore.hydrate(data));
98+
protected async savePayload(
99+
request: Request,
100+
response: Response,
101+
checkExists: boolean = false,
102+
validatorOptions: ValidatorOptions = {},
103+
): Promise<Response> | never {
107104

108-
if (checkExists) {
109-
110-
modelPayload = modelPayload.then((payload: M) => {
111-
return this.modelStore.hasOne(payload)
112-
.then((exists: boolean) => {
113-
if (!exists) {
114-
throw new NotFoundException(`Model with id [${payload.getIdentifier()}] does not exist`);
115-
}
116-
return payload;
117-
});
118-
})
105+
const model = await this.modelStore.hydrate(await request.getPayload());
119106

107+
if (checkExists) {
108+
const exists = await this.modelStore.hasOne(model);
109+
if (!exists) {
110+
throw new NotFoundException(`Model with id [${model.getIdentifier()}] does not exist`);
111+
}
120112
}
121113

122-
return modelPayload
123-
.then((model: M) => this.modelStore.validate(model, validatorOptions))
124-
.then((model: M) => this.modelStore.saveOne(model))
125-
.then((model: M) => response.data(model));
114+
await this.modelStore.validate(model, validatorOptions);
115+
await this.modelStore.saveOne(model);
116+
return response.data(model);
126117
}
127118

128119
}

src/server/middleware/debugLog.middleware.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -64,8 +64,7 @@ export class DebugLogMiddleware implements InjectableMiddleware {
6464
export function debugLog(...messages: string[]): InjectableMiddlewareFactory {
6565

6666
return (injector: ReflectiveInjector): Middleware => {
67-
return injector.get(DebugLogMiddleware)
68-
.middlewareFactory(messages);
67+
return injector.get(DebugLogMiddleware).middlewareFactory(messages);
6968
}
7069

7170
}

src/server/services/jwtAuthStrategy.ts

Lines changed: 16 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ import {
1414

1515
export const jwtAuthStrategyFactory:AuthenticationStrategyFactory = (remoteCliContext: RemoteCliContext): AuthenticationStrategy => {
1616
return function (vantage: any, options: any) {
17-
return function (args: {client: {jwt: string, publicKeyPath: string, columns: number}}, cb: AuthenticationCallback) {
17+
return async function (args: {client: {jwt: string, publicKeyPath: string, columns: number}}, cb: AuthenticationCallback) {
1818

1919
try {
2020
remoteCliContext.logger.silly.debug('Passed client arguments: ', args);
@@ -32,23 +32,21 @@ export const jwtAuthStrategyFactory:AuthenticationStrategyFactory = (remoteCliCo
3232

3333
remoteCliContext.logger.info(`Authenticating JSON web token against public key [${keyPath}]`);
3434

35-
remoteCliContext.authService.verify(token, keyPath)
36-
.then((payload: any) => {
37-
remoteCliContext.logger.info(`${payload.username} has been authenticated with token`)
38-
.debug('Token:', token);
39-
let displayBanner = `Hi ${payload.username}, Welcome to Zeroth runtime cli.`;
40-
if (args.client.columns >= 80) {
41-
displayBanner = bannerBg(undefined, token);
42-
}
43-
this.log(chalk.grey(`You were authenticated with a JSON Web token verified against the public key at ${keyPath}`));
44-
this.log(displayBanner);
45-
this.log(` Type 'help' for a list of available commands`);
46-
47-
return cb(null, true);
48-
})
49-
.catch((e: Error) => {
50-
return cb(e.message, false);
51-
});
35+
const payload = await remoteCliContext.authService.verify(token, keyPath);
36+
37+
remoteCliContext.logger.info(`${payload.username} has been authenticated with token`)
38+
.debug('Token:', token);
39+
40+
let displayBanner = `Hi ${payload.username}, Welcome to Zeroth runtime cli.`;
41+
if (args.client.columns >= 80) {
42+
displayBanner = bannerBg(undefined, token);
43+
}
44+
45+
this.log(chalk.grey(`You were authenticated with a JSON Web token verified against the public key at ${keyPath}`));
46+
this.log(displayBanner);
47+
this.log(` Type 'help' for a list of available commands`);
48+
49+
return cb(null, true);
5250

5351
} catch (e) {
5452
remoteCliContext.logger.error('Authentication error', e.message).debug(e.stack);

src/server/stores/db.store.ts

Lines changed: 32 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -73,50 +73,54 @@ export abstract class DatabaseStore<T extends AbstractModel> extends AbstractSto
7373
/**
7474
* @inheritdoc
7575
*/
76-
public findMany(query?: Query): Promise<Collection<T>> {
77-
return this.getRepository()
78-
.then((repo) => repo.find({
79-
//@todo define query and restrict count with pagination
80-
}))
81-
.then((entityArray: T[]): Collection<T> => {
82-
83-
if (!entityArray.length) {
84-
throw new NotFoundException(`No ${this.modelStatic.name} found with query params [${JSON.stringify(query)}]`);
85-
}
86-
87-
return new Collection(entityArray);
88-
})
89-
.catch((e) => {
90-
this.logger.error(e);
91-
throw e;
76+
public async findMany(query?: Query): Promise<Collection<T>> {
77+
78+
try {
79+
const repo = await this.getRepository();
80+
81+
const entityArray: T[] = await repo.find({
82+
//@todo define query interface and restrict count with pagination
9283
});
84+
85+
if (!entityArray.length) {
86+
throw new NotFoundException(`No ${this.modelStatic.name} found with query params [${JSON.stringify(query)}]`);
87+
}
88+
89+
return new Collection(entityArray);
90+
91+
} catch (e) {
92+
this.logger.error(e);
93+
throw e;
94+
}
9395
}
9496

9597
/**
9698
* @inheritdoc
9799
*/
98-
public saveOne(model: T): Promise<T> {
99-
return this.getRepository()
100-
.then((repo) => repo.persist(model));
100+
public async saveOne(model: T): Promise<T> {
101+
const repo = await this.getRepository();
102+
return repo.persist(model);
101103
}
102104

103105
/**
104106
* @inheritdoc
105107
*/
106-
public deleteOne(model: T): Promise<T> {
107-
return this.getRepository()
108-
.then((repo) => repo.remove(model));
108+
public async deleteOne(model: T): Promise<T> {
109+
const repo = await this.getRepository();
110+
return repo.remove(model);
109111
}
110112

111113
/**
112114
* @inheritdoc
113115
*/
114-
public hasOne(model: T): Promise<boolean> {
115-
return this.getRepository()
116-
.then((repo) => repo.findOneById(model))
117-
.then(() => true)
118-
.catch(() => false)
119-
;
116+
public async hasOne(model: T): Promise<boolean> {
117+
const repo = await this.getRepository();
118+
try {
119+
await repo.findOneById(model.getIdentifier());
120+
return true;
121+
} catch (e) {
122+
return false;
123+
}
120124
}
121125

122126
}

0 commit comments

Comments
 (0)