import { buildSubgraphSchema } from '@apollo/subgraph';
import { parse } from 'graphql';
import { printSchema, GraphQLObjectType, GraphQLList, GraphQLScalarType } from 'graphql';
import { generateSubServiceResolvers } from './resolvers.js';
export const buildFederatedSubscriptionSchema = (subServices, config, namespace, schema) => {
    const resolvers = generateSubServiceResolvers(subServices, config, namespace);
    // TODO There is currently no way of building a federated schema from GraphQLSchema Object
    // See https://github.com/apollographql/apollo-server/pull/4310
    const federatedSchema = buildSubgraphSchema([{
            typeDefs: parse(printSchema(schema)),
            resolvers
        }]);
    return {
        federatedSchema,
        resolvers
    };
};
export const mergeSubscribeIntoSchema = (schema, resolvers) => {
    if (!schema || !resolvers) {
        return;
    }
    Object.entries(resolvers).forEach(([key, val]) => {
        if (schema instanceof GraphQLList) {
            mergeSubscribeIntoSchema(schema.ofType, val);
            return;
        }
        const field = schema.getFields()[key];
        if (!field) {
            return;
        }
        if ('resolve' in val || 'subscribe' in val) {
            field.subscribe = val['subscribe'] || field.subscribe;
            field.resolve = val['resolve'] || field.resolve;
            return;
        }
        const fieldType = field.type;
        if (fieldType instanceof GraphQLScalarType) {
            field.subscribe = val['subscribe'];
        }
        else if (fieldType instanceof GraphQLObjectType) {
            mergeSubscribeIntoSchema(fieldType, val);
        }
    });
};
//# sourceMappingURL=federation.js.map