import { Timestamp } from "@google-cloud/firestore"; import { AuthInfo } from "@pie-api-gcp/shared/auth"; import { getLogger } from "@pie-api-gcp/shared/logging"; import { DateTime, DateTimeScalar, EmailAddress, EmailAddressScalar, URL, URLScalar } from "@okgrow/graphql-scalars"; import { gql } from "apollo-server"; import { GraphQLError, GraphQLScalarType, Kind } from "graphql"; import { isObject } from "lodash"; import { VersionedIDHelper } from "@pie-api-gcp/datastore/version"; import { VersionedID as IVersionedID } from "@pie-api-gcp/datastore/types"; import { GraphQLSchemaFactory, GraphQLSchemaElements } from "../types"; const logger = getLogger(); export const JSONScalar = gql` scalar JSON `; export const VersionedIDScalar = gql` scalar VersionedID `; export const FirestoreTimestampScalar = gql` scalar FirestoreTimestamp `; export const VersionedID = new GraphQLScalarType({ name: "VersionedID", description: 'Versioned ID string: "id@version"', serialize(value) { if (isObject(value)) { throw new TypeError(`Value is not string: ${value}`); } const v = value as IVersionedID; if (v.id || v.semver) { throw new TypeError(`Value is not a valid versioned ID object: ${v}`); } return VersionedIDHelper.encode(v); }, parseValue(value) { if (typeof value !== "string") { throw new TypeError("Value is not string"); } return VersionedIDHelper.decode(value); }, parseLiteral(ast) { if (ast.kind !== Kind.STRING) { throw new GraphQLError(`Can only validate strings as versioned ID(s) but got a: ${ast.kind}`); } return VersionedIDHelper.decode(ast.value); }, }); export const FirestoreTimestamp = new GraphQLScalarType({ name: "FirestoreTimestamp", description: "FirestoreTimestamp scalar type", serialize(date: Timestamp) { return date.toDate(); }, parseValue(value) { const date = new Date(value); if (Number.isNaN(date.getTime())) { throw new TypeError(`Value is not a valid Date: ${JSON.stringify(value)}`); } return Timestamp.fromDate(date); }, parseLiteral(ast) { if (ast.kind === Kind.INT) { return Timestamp.fromDate(new Date(parseInt(ast.value, 10))); } if (ast.kind === Kind.STRING) { if (this.parseValue) return this.parseValue(ast.value); } return null; }, }); export const customScalarDefinitions = [ DateTimeScalar, EmailAddressScalar, URLScalar, VersionedIDScalar, FirestoreTimestampScalar, JSONScalar, ]; export const customScalars = { DateTime, EmailAddress, URL, VersionedID, }; // in order to extend Query and Mutation elsewhere, we need a 'root' object for both, which // unfortunately can't be defined empty const schemaFactory: GraphQLSchemaFactory = async (token: AuthInfo): Promise => ({ typeDefs: customScalarDefinitions, resolvers: { ...customScalars, }, }); export default schemaFactory;