All files / services/api api.service.ts

0% Statements 0/66
0% Branches 0/24
0% Functions 0/12
0% Lines 0/64

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153                                                                                                                                                                                                                                                                                                                 
import { createVersedAxiosClient } from "@versed/core";
import authSpec from "@schemas/services/auth/auth.v1.service.json";
import tokenSpec from "@schemas/services/token/token.v1.service.json";
import userSpec from "@schemas/services/user/user.v1.service.json";
import blogSpec from "@schemas/services/blog/blog.v1.service.json";
import resumeSpec from "@schemas/services/resume/resume.v1.service.json";
import { IVersedService } from "@versed/contract";
import { IBSResumeService } from "@schemas/services/resume/resume.v1.service";
import { IAuthService } from "@schemas/services/auth/auth.v1.service";
import { ITokenService } from "@schemas/services/token/token.v1.service";
import { IUserService } from "@schemas/services/user/user.v1.service";
import Router from "@koa/router";
import v1Endpoints from "./endpoints/v1";
import { APIDefinition } from "@services/api/endpoints/definition-utils";
import flat from "flat";
import validate from "@mod/joi/validate";
import { Context } from "@versed/context";
import { NotFoundError } from "@versed/error";
import config from "../../../config/config";
import { IBSBlog } from "@schemas/services/blog/blog.v1.service";
 
const client = createVersedAxiosClient();
const serviceMap = {
  resume: client.createService<IBSResumeService>(resumeSpec, {
    basePath: config.services.resume.url.get(),
  }),
  user: client.createService<IUserService>(userSpec, {
    basePath: config.services.user.url.get(),
  }),
  token: client.createService<ITokenService>(tokenSpec, {
    basePath: config.services.token.url.get(),
  }),
  auth: client.createService<IAuthService>(authSpec, {
    basePath: config.services.auth.url.get(),
  }),
  blog: client.createService<IBSBlog>(blogSpec, {
    basePath: config.services.blog.url.get(),
  }),
};
 
export default class APIGatewayService implements IVersedService {
  router = new Router();
 
  async init(ctx: Context) {
    await this.koaInit(ctx, "/v1", v1Endpoints);
  }
 
  async koaInit(ctx: Context, prefix: string, apis: APIDefinition[]) {
    // Init Routers
    const { router } = this;
 
    // Register all apis to router
    apis.forEach(api => {
      // parse the definition
      if (typeof api.handler === "string") {
        const [serviceName, methodName] = api.handler.split(".");
        api.handlerId = api.handlerId || api.handler;
        api.handler = async ctx => {
          const service = serviceMap[serviceName];
          if (!service[methodName]) {
            ctx.logger.warn("service or method not found", {
              serviceName,
              methodName,
            });
            throw new NotFoundError();
          }
          return await service[methodName](ctx, (ctx.meta as any).params);
        };
      }
 
      // register to router
      if (router[api.method.toLowerCase()]) {
        ctx.logger.info("register api path:", api.path);
        router[api.method.toLowerCase()](prefix + api.path, async (koaCtx, next) => {
          // set context meta
          koaCtx.versedCtx = ctx.child(api.path);
 
          return await this.handleRequest(koaCtx, api);
        });
      }
    });
  }
 
  async handleRequest(koaCtx, api: APIDefinition) {
    const ctx = koaCtx.versedCtx;
    const requestMeta: any = {};
 
    // request validation
    const params = {};
    // Get Params from url
    Object.assign(params, koaCtx.params);
 
    if (api.request) {
      const koaParseParams = params => {
        const flattedParams = flat(params);
        for (const itemKey of Object.keys(flattedParams)) {
          try {
            flattedParams[itemKey] = JSON.parse(flattedParams[itemKey]);
            // eslint-disable-next-line no-empty
          } catch (e) {}
        }
        return flat.unflatten(flattedParams);
      };
 
      // Validate Query
      if (api.request.query) {
        const validated = await validate(
          ctx,
          api.request.query,
          koaParseParams(koaCtx.request.query),
        );
        Object.assign(params, validated);
      }
 
      // Validate Body
      if (api.request.body) {
        const validated = await validate(ctx, api.request.body, koaCtx.request.body);
        Object.assign(params, validated);
      }
 
      // Validate Cookie
      if (api.request.cookie) {
        const validated = await validate(ctx, api.request.cookie, koaCtx.request.cookie);
        Object.assign(params, validated);
      }
    }
 
    requestMeta.params = params;
 
    // extract authorization
    if (koaCtx.headers["authorization"]) {
      const [type, value] = koaCtx.headers["authorization"].split(" ");
      if (type === "Bearer") {
        requestMeta.accessToken = value;
      }
    }
 
    // inject meta to versed ctx
    Object.assign(ctx.meta, requestMeta);
 
    // security policy
    if (api.securityPolicy) {
      const response = await api.securityPolicy(koaCtx.versedCtx, () => {});
      if (response) {
        return response;
      }
    }
 
    // @ts-ignore
    return await api.handler(koaCtx.versedCtx, () => {});
  }
}