UNPKG

kritsana135-hooray-server

Version:

for server

56 lines (54 loc) 1.66 kB
import { ApolloError } from "apollo-server" import AppModel from "../models/AppModel" import { EN } from "../constants/language" import { APP_NOT_FOUND, CORE_SERVICE_NOT_FOUND, FEATURE_NOT_FOUND, FEATURE_NOT_ENABLE, } from "../constants/errors/application" import ErrorMessage from "./error" import { connection } from "mongoose" export const checkFeatureKey = async ( locale = EN, credentialKey = "", coreServiceKey = "", featureKeys = [], errorMessage = true, connection ) => { const app = await AppModel(connection) .findOne({ credentials: { $elemMatch: { credentialKey } }, }) .populate({ path: "services.service", }) .populate({ path: "theme", select: "-__v" }) if (!app) throw ErrorMessage(locale, APP_NOT_FOUND) const service = app?.services?.find( (element) => element.service?.serviceKey === coreServiceKey ) if (!service) throw ErrorMessage(locale, CORE_SERVICE_NOT_FOUND) if (!Array.isArray(featureKeys)) throw new ApolloError("Invalid featureKey", "INVALID_FEATURE_KEY") // check Feature const result = {} featureKeys.forEach((element) => { const checkFeature = service.featureKeys?.find( (element2) => element2.key === element ) if (errorMessage) { if (!checkFeature) throw ErrorMessage(locale, FEATURE_NOT_FOUND) if (!checkFeature.enable) { throw new ApolloError( checkFeature.key + FEATURE_NOT_ENABLE.message[locale], FEATURE_NOT_ENABLE.code ) } // return true } else if (!checkFeature) result[element] = false else result[element] = checkFeature.enable }) return result }