import { SearchSchemaRepository } from "@pie-api-gcp/datastore/repositories"; import { SearchSchemaService } from "@pie-api-gcp/datastore/services"; import { AuthInfo } from "@pie-api-gcp/shared/auth"; import { getLogger } from "@pie-api-gcp/shared/logging"; import { gql } from "apollo-server"; import { AuthorizationError } from "../errors"; import { GraphQLSchemaFactory, ResultFunctionContext, GraphQLSchemaElements } from "../types"; import { adminOnlyResolver, protectedResolver } from "../resolver"; const logger = getLogger(); const Schema = gql` type SearchSchema { id: ID! properties: JSON } input CreateSearchSchemaInput { id: String! properties: JSON } extend type Query { searchSchema(id: ID!): SearchSchema allSearchSchemas: [SearchSchema] } extend type Mutation { createSearchSchema(input: CreateSearchSchemaInput): SearchSchema } `; const searchSchema = adminOnlyResolver(async (_, args, { authInfo }: ResultFunctionContext) => { const { id } = args; const schema = await SearchSchemaRepository.findById(id); if (!authInfo.admin) { // TODO [Eelco] optimize const searchSchemaService = new SearchSchemaService(); const availableSchemas = await searchSchemaService.findForOrganization(authInfo.organizationId); if (availableSchemas.filter((s) => s.id === id).length === 0) { throw new AuthorizationError("You are not authorized for this resource"); } } return schema; }); const allSearchSchemas = protectedResolver(async (_, args, { authInfo }: ResultFunctionContext) => { const searchSchemaService = new SearchSchemaService(); const searchSchemas = authInfo.admin ? await searchSchemaService.findAll() : await searchSchemaService.findForOrganization(authInfo.organizationId); return searchSchemas; }); const createSearchSchema = adminOnlyResolver(async (_, args, {}: ResultFunctionContext) => { const { input } = args; const clone = SearchSchemaRepository.deepCloneSearchSchema(input, true); return SearchSchemaRepository.upsert(clone, { replace: true }); }); const schemaFactory: GraphQLSchemaFactory = async (token: AuthInfo): Promise => ({ typeDefs: [Schema], resolvers: { Query: { searchSchema, allSearchSchemas, }, Mutation: { createSearchSchema, }, }, }); export default schemaFactory;