"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.SchemaLink = void 0;
const graphql_1 = require("graphql");
const rxjs_1 = require("rxjs");
const link_1 = require("@apollo/client/link");
class SchemaLink extends link_1.ApolloLink {
    schema;
    rootValue;
    context;
    validate;
    constructor(options) {
        super();
        this.schema = options.schema;
        this.rootValue = options.rootValue;
        this.context = options.context;
        this.validate = !!options.validate;
    }
    request(operation) {
        return new rxjs_1.Observable((observer) => {
            new Promise((resolve) => resolve(typeof this.context === "function" ?
                this.context(operation)
                : this.context))
                .then((context) => {
                if (this.validate) {
                    const validationErrors = (0, graphql_1.validate)(this.schema, operation.query);
                    if (validationErrors.length > 0) {
                        return { errors: validationErrors };
                    }
                }
                return (0, graphql_1.execute)({
                    schema: this.schema,
                    document: operation.query,
                    rootValue: this.rootValue,
                    contextValue: context,
                    variableValues: operation.variables,
                    operationName: operation.operationName,
                });
            })
                .then((data) => {
                if (!observer.closed) {
                    observer.next(data);
                    observer.complete();
                }
            })
                .catch((error) => {
                if (!observer.closed) {
                    observer.error(error);
                }
            });
        });
    }
}
exports.SchemaLink = SchemaLink;
//# sourceMappingURL=index.cjs.map
