Route Handlers (Express.js)

JS
S
JavaScript

Concise guide for creating and managing Express.js route handlers to handle HTTP requests and define application endpoints efficiently.

1function Get(param?: string, type?: string): any {
2  param = param || '/';
3  return (target: any, propertyKey: string): TypedPropertyDescriptor<any> => {
4    const descriptor = Object.getOwnPropertyDescriptor(target, propertyKey);
5    const originalMethod = descriptor.value;
6    target._routes = target._routes || [];
7    function asyncMiddleware(request: Request, response: Response, next: NextFunction) {
8      const promise = originalMethod(request, response, next);
9      if (promise && promise.then) {
10        promise
11          .then((result: any) => {
12            if (!result) {
13              response.status(404).send({ error: 'Document not found' });
14            } else {
15              response.status(200);
16              if (type === 'html') {
17                response.send(result);
18              } else if (type === 'array') {
19                response.send(getResponseBluePrint(result));
20              } else if (type === 'paginated') {
21                response.send(result);
22              } else if (type === 'raw') {
23                response.send(result);
24              } else {
25                response.send(getAtomicResponseBluePrint(result));
26              }
27            }
28          })
29          .catch((err: Error) => next(err));
30      }
31    }
32    target._routes.push({
33      url: param,
34      method: 'get',
35      handler: asyncMiddleware,
36    });
37    return descriptor;
38  };
39}
40
41
42//
43const getResponseBluePrint = (data: any) => {
44  const obj = Object.assign({}, ArrayDataResponseBluePrint);
45  obj.resultCount = data.length;
46  obj.results = data;
47  return obj;
48};

Created on 2/24/2021