import { execute, validate } from "graphql";
import { Observable } from "rxjs";
import { ApolloLink } from "@apollo/client/link";
export class SchemaLink extends 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 Observable((observer) => {
            new Promise((resolve) => resolve(typeof this.context === "function" ?
                this.context(operation)
                : this.context))
                .then((context) => {
                if (this.validate) {
                    const validationErrors = validate(this.schema, operation.query);
                    if (validationErrors.length > 0) {
                        return { errors: validationErrors };
                    }
                }
                return 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);
                }
            });
        });
    }
}
//# sourceMappingURL=index.js.map
