Asynchronous Decorator (typescript)

JS
S
JavaScript

Demonstrates how to create and use asynchronous decorators in TypeScript, enhancing function behavior with non-blocking operations.

1import { UserModel } from '../models/user.model';
2
3import { UserFacingError, PublicAPIError, ErrorTypes } from '../classes/errors';
4import logService from '../services/log';
5
6const defaultMsg = 'There is an already existing user';
7
8const getUser = async (id: string) => {
9  return  UserModel.findOne()
10};
11
12export function ValidateUniqueness(callType?: string) {
13  return (target: any, key: any, descriptor: any) => {
14    const fn = descriptor.value;
15    descriptor.value = async function (...args: any[]) {
16      let isInvalid = false;
17      const request = args[0];
18      const { method, query, body, params } = request;
19      if (method === 'POST' || method === 'PUT') {
20        const hasProp = body.hasOwnProperty('meterDetails');
21        if (!hasProp) {
22          isInvalid = true;
23        } else {
24          const existingUser = await getUser(id);
25          logService.log('info', 'User', { v });
26          if (existingUser.length > 0) {
27            if (callType === 'public') {
28              throw new PublicAPIError(defaultMsg, ErrorTypes.existingUser);
29            } else {
30              throw new UserFacingError(defaultMsg, { code: 400 });
31            }
32          }
33        }
34      }
35      return fn.apply(this, args);
36    };
37  };
38}
39

Created on 7/8/2020