Initial Save

This commit is contained in:
jackbeeby
2025-03-28 12:30:19 +11:00
parent e381994f19
commit d8773925e8
9910 changed files with 982718 additions and 0 deletions

21
node_modules/apollo-server-express/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2016-2020 Apollo Graph, Inc. (Formerly Meteor Development Group, Inc.)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

102
node_modules/apollo-server-express/README.md generated vendored Normal file
View File

@@ -0,0 +1,102 @@
[![npm version](https://badge.fury.io/js/apollo-server-express.svg)](https://badge.fury.io/js/apollo-server-express)
[![Build Status](https://circleci.com/gh/apollographql/apollo-server/tree/main.svg?style=svg)](https://circleci.com/gh/apollographql/apollo-server)
[![Join the community forum](https://img.shields.io/badge/join%20the%20community-forum-blueviolet)](https://community.apollographql.com)
[![Read CHANGELOG](https://img.shields.io/badge/read-changelog-blue)](https://github.com/apollographql/apollo-server/blob/HEAD/CHANGELOG.md)
This is the Express and Connect integration of GraphQL Server. Apollo Server is a community-maintained open-source GraphQL server that works with many Node.js HTTP server frameworks. [Read the docs](https://www.apollographql.com/docs/apollo-server/). [Read the CHANGELOG.](https://github.com/apollographql/apollo-server/blob/main/CHANGELOG.md)
```shell
npm install apollo-server-express graphql
```
## Express
```js
const express = require('express');
const { ApolloServer, gql } = require('apollo-server-express');
async function startApolloServer() {
// Construct a schema, using GraphQL schema language
const typeDefs = gql`
type Query {
hello: String
}
`;
// Provide resolver functions for your schema fields
const resolvers = {
Query: {
hello: () => 'Hello world!',
},
};
const server = new ApolloServer({ typeDefs, resolvers });
await server.start();
const app = express();
server.applyMiddleware({ app });
await new Promise(resolve => app.listen({ port: 4000 }, resolve));
console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`);
return { server, app };
}
```
## Connect
> We recommend using `express` rather than `connect`. However, if you wish to
> use `connect`, please install [`connect`](https://www.npmjs.com/package/connect)
> and [`qs-middleware`](https://www.npmjs.com/package/qs-middleware), in addition
> to `apollo-server-express`.
```shell
npm install --save connect qs-middleware apollo-server-express graphql
```
```js
const connect = require('connect');
const { ApolloServer, gql } = require('apollo-server-express');
const query = require('qs-middleware');
async function startApolloServer() {
// Construct a schema, using GraphQL schema language
const typeDefs = gql`
type Query {
hello: String
}
`;
// Provide resolver functions for your schema fields
const resolvers = {
Query: {
hello: () => 'Hello world!',
},
};
const server = new ApolloServer({ typeDefs, resolvers });
await server.start();
const app = connect();
const path = '/graphql';
app.use(query());
server.applyMiddleware({ app, path });
await new Promise(resolve => app.listen({ port: 4000 }, resolve));
console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`);
return { server, app };
}
```
> Note: `qs-middleware` is only required if running outside of Meteor
## Principles
GraphQL Server is built with the following principles in mind:
* **By the community, for the community**: GraphQL Server's development is driven by the needs of developers
* **Simplicity**: by keeping things simple, GraphQL Server is easier to use, easier to contribute to, and more secure
* **Performance**: GraphQL Server is well-tested and production-ready - no modifications needed
Anyone is welcome to contribute to GraphQL Server, just read [CONTRIBUTING.md](https://github.com/apollographql/apollo-server/blob/main/CONTRIBUTING.md), take a look at the [roadmap](https://github.com/apollographql/apollo-server/blob/main/ROADMAP.md) and make your first PR!

View File

@@ -0,0 +1,33 @@
import express from 'express';
import corsMiddleware from 'cors';
import { OptionsJson } from 'body-parser';
import { GraphQLOptions, ApolloServerBase, ContextFunction, Context, Config } from 'apollo-server-core';
import type { ExecutionParams } from 'subscriptions-transport-ws';
export { GraphQLOptions, GraphQLExtension } from 'apollo-server-core';
export interface GetMiddlewareOptions {
path?: string;
cors?: corsMiddleware.CorsOptions | corsMiddleware.CorsOptionsDelegate | boolean;
bodyParserConfig?: OptionsJson | boolean;
onHealthCheck?: (req: express.Request) => Promise<any>;
disableHealthCheck?: boolean;
}
export interface ServerRegistration extends GetMiddlewareOptions {
app: express.Application;
}
export interface ExpressContext {
req: express.Request;
res: express.Response;
connection?: ExecutionParams;
}
export interface ApolloServerExpressConfig extends Config {
context?: ContextFunction<ExpressContext, Context> | Context;
}
export declare class ApolloServer extends ApolloServerBase {
constructor(config: ApolloServerExpressConfig);
createGraphQLServerOptions(req: express.Request, res: express.Response): Promise<GraphQLOptions>;
protected supportsSubscriptions(): boolean;
protected supportsUploads(): boolean;
applyMiddleware({ app, ...rest }: ServerRegistration): void;
getMiddleware({ path, cors, bodyParserConfig, disableHealthCheck, onHealthCheck, }?: GetMiddlewareOptions): express.Router;
}
//# sourceMappingURL=ApolloServer.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ApolloServer.d.ts","sourceRoot":"","sources":["../src/ApolloServer.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,SAAS,CAAC;AAC9B,OAAO,cAAc,MAAM,MAAM,CAAC;AAClC,OAAO,EAAQ,WAAW,EAAE,MAAM,aAAa,CAAC;AAKhD,OAAO,EACL,cAAc,EAEd,gBAAgB,EAGhB,eAAe,EACf,OAAO,EACP,MAAM,EACP,MAAM,oBAAoB,CAAC;AAC5B,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAKlE,OAAO,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAEtE,MAAM,WAAW,oBAAoB;IACnC,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,IAAI,CAAC,EAAE,cAAc,CAAC,WAAW,GAAG,cAAc,CAAC,mBAAmB,GAAG,OAAO,CAAC;IACjF,gBAAgB,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC;IACzC,aAAa,CAAC,EAAE,CAAC,GAAG,EAAE,OAAO,CAAC,OAAO,KAAK,OAAO,CAAC,GAAG,CAAC,CAAC;IACvD,kBAAkB,CAAC,EAAE,OAAO,CAAC;CAC9B;AAED,MAAM,WAAW,kBAAmB,SAAQ,oBAAoB;IAO9D,GAAG,EAAE,OAAO,CAAC,WAAW,CAAC;CAC1B;AAoCD,MAAM,WAAW,cAAc;IAC7B,GAAG,EAAE,OAAO,CAAC,OAAO,CAAC;IACrB,GAAG,EAAE,OAAO,CAAC,QAAQ,CAAC;IACtB,UAAU,CAAC,EAAE,eAAe,CAAC;CAC9B;AAED,MAAM,WAAW,yBAA0B,SAAQ,MAAM;IACvD,OAAO,CAAC,EAAE,eAAe,CAAC,cAAc,EAAE,OAAO,CAAC,GAAG,OAAO,CAAC;CAC9D;AAED,qBAAa,YAAa,SAAQ,gBAAgB;gBACpC,MAAM,EAAE,yBAAyB;IAOvC,0BAA0B,CAC9B,GAAG,EAAE,OAAO,CAAC,OAAO,EACpB,GAAG,EAAE,OAAO,CAAC,QAAQ,GACpB,OAAO,CAAC,cAAc,CAAC;IAI1B,SAAS,CAAC,qBAAqB,IAAI,OAAO;IAI1C,SAAS,CAAC,eAAe,IAAI,OAAO;IAI7B,eAAe,CAAC,EAAE,GAAG,EAAE,GAAG,IAAI,EAAE,EAAE,kBAAkB;IAOpD,aAAa,CAAC,EACnB,IAAI,EACJ,IAAI,EACJ,gBAAgB,EAChB,kBAAkB,EAClB,aAAa,GACd,GAAE,oBAAyB,GAAG,OAAO,CAAC,MAAM;CA8F9C"}

143
node_modules/apollo-server-express/dist/ApolloServer.js generated vendored Normal file
View File

@@ -0,0 +1,143 @@
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ApolloServer = void 0;
const express_1 = __importDefault(require("express"));
const cors_1 = __importDefault(require("cors"));
const body_parser_1 = require("body-parser");
const graphql_playground_html_1 = require("@apollographql/graphql-playground-html");
const apollo_server_core_1 = require("apollo-server-core");
const accepts_1 = __importDefault(require("accepts"));
const type_is_1 = __importDefault(require("type-is"));
const expressApollo_1 = require("./expressApollo");
var apollo_server_core_2 = require("apollo-server-core");
Object.defineProperty(exports, "GraphQLExtension", { enumerable: true, get: function () { return apollo_server_core_2.GraphQLExtension; } });
const fileUploadMiddleware = (uploadsConfig, server) => (req, res, next) => {
if (!server.disableUploads() &&
typeof apollo_server_core_1.processFileUploads === 'function' &&
type_is_1.default(req, ['multipart/form-data'])) {
apollo_server_core_1.processFileUploads(req, res, uploadsConfig)
.then(body => {
req.body = body;
next();
})
.catch(error => {
if (error.status && error.expose)
res.status(error.status);
next(apollo_server_core_1.formatApolloErrors([error], {
formatter: server.requestOptions.formatError,
debug: server.requestOptions.debug,
}));
});
}
else {
next();
}
};
class ApolloServer extends apollo_server_core_1.ApolloServerBase {
constructor(config) {
super(config);
}
createGraphQLServerOptions(req, res) {
const _super = Object.create(null, {
graphQLServerOptions: { get: () => super.graphQLServerOptions }
});
return __awaiter(this, void 0, void 0, function* () {
return _super.graphQLServerOptions.call(this, { req, res });
});
}
supportsSubscriptions() {
return true;
}
supportsUploads() {
return true;
}
applyMiddleware(_a) {
var { app } = _a, rest = __rest(_a, ["app"]);
app.use(this.getMiddleware(rest));
}
getMiddleware({ path, cors, bodyParserConfig, disableHealthCheck, onHealthCheck, } = {}) {
if (!path)
path = '/graphql';
this.ensureStarting();
const router = express_1.default.Router();
if (!disableHealthCheck) {
router.use('/.well-known/apollo/server-health', (req, res) => {
res.type('application/health+json');
if (onHealthCheck) {
onHealthCheck(req)
.then(() => {
res.json({ status: 'pass' });
})
.catch(() => {
res.status(503).json({ status: 'fail' });
});
}
else {
res.json({ status: 'pass' });
}
});
}
let uploadsMiddleware;
if (this.uploadsConfig && typeof apollo_server_core_1.processFileUploads === 'function') {
uploadsMiddleware = fileUploadMiddleware(this.uploadsConfig, this);
}
this.graphqlPath = path;
if (cors === true) {
router.use(path, cors_1.default());
}
else if (cors !== false) {
router.use(path, cors_1.default(cors));
}
if (bodyParserConfig === true) {
router.use(path, body_parser_1.json());
}
else if (bodyParserConfig !== false) {
router.use(path, body_parser_1.json(bodyParserConfig));
}
if (uploadsMiddleware) {
router.use(path, uploadsMiddleware);
}
router.use(path, (req, res, next) => {
if (this.playgroundOptions && req.method === 'GET') {
const accept = accepts_1.default(req);
const types = accept.types();
const prefersHTML = types.find((x) => x === 'text/html' || x === 'application/json') === 'text/html';
if (prefersHTML) {
const playgroundRenderPageOptions = Object.assign({ endpoint: req.originalUrl, subscriptionEndpoint: this.subscriptionsPath }, this.playgroundOptions);
res.setHeader('Content-Type', 'text/html');
const playground = graphql_playground_html_1.renderPlaygroundPage(playgroundRenderPageOptions);
res.write(playground);
res.end();
return;
}
}
return expressApollo_1.graphqlExpress(() => this.createGraphQLServerOptions(req, res))(req, res, next);
});
return router;
}
}
exports.ApolloServer = ApolloServer;
//# sourceMappingURL=ApolloServer.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"ApolloServer.js","sourceRoot":"","sources":["../src/ApolloServer.ts"],"names":[],"mappings":"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"}

View File

@@ -0,0 +1,3 @@
import { graphqlExpress } from './expressApollo';
export declare const graphqlConnect: typeof graphqlExpress;
//# sourceMappingURL=connectApollo.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"connectApollo.d.ts","sourceRoot":"","sources":["../src/connectApollo.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAEjD,eAAO,MAAM,cAAc,uBAAiB,CAAC"}

View File

@@ -0,0 +1,6 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.graphqlConnect = void 0;
const expressApollo_1 = require("./expressApollo");
exports.graphqlConnect = expressApollo_1.graphqlExpress;
//# sourceMappingURL=connectApollo.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"connectApollo.js","sourceRoot":"","sources":["../src/connectApollo.ts"],"names":[],"mappings":";;;AAAA,mDAAiD;AAEpC,QAAA,cAAc,GAAG,8BAAc,CAAC"}

View File

@@ -0,0 +1,8 @@
import express from 'express';
import { GraphQLOptions } from 'apollo-server-core';
import { ValueOrPromise } from 'apollo-server-types';
export interface ExpressGraphQLOptionsFunction {
(req: express.Request, res: express.Response): ValueOrPromise<GraphQLOptions>;
}
export declare function graphqlExpress(options: GraphQLOptions | ExpressGraphQLOptionsFunction): express.Handler;
//# sourceMappingURL=expressApollo.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"expressApollo.d.ts","sourceRoot":"","sources":["../src/expressApollo.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,SAAS,CAAC;AAC9B,OAAO,EACL,cAAc,EAIf,MAAM,oBAAoB,CAAC;AAC5B,OAAO,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAErD,MAAM,WAAW,6BAA6B;IAC5C,CAAC,GAAG,EAAE,OAAO,CAAC,OAAO,EAAE,GAAG,EAAE,OAAO,CAAC,QAAQ,GAAG,cAAc,CAAC,cAAc,CAAC,CAAC;CAC/E;AAOD,wBAAgB,cAAc,CAC5B,OAAO,EAAE,cAAc,GAAG,6BAA6B,GACtD,OAAO,CAAC,OAAO,CAuDjB"}

View File

@@ -0,0 +1,50 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.graphqlExpress = void 0;
const apollo_server_core_1 = require("apollo-server-core");
function graphqlExpress(options) {
if (!options) {
throw new Error('Apollo Server requires options.');
}
if (arguments.length > 1) {
throw new Error(`Apollo Server expects exactly one argument, got ${arguments.length}`);
}
return (req, res, next) => {
apollo_server_core_1.runHttpQuery([req, res], {
method: req.method,
options: options,
query: req.method === 'POST' ? req.body : req.query,
request: apollo_server_core_1.convertNodeHttpToRequest(req),
}).then(({ graphqlResponse, responseInit }) => {
if (responseInit.headers) {
for (const [name, value] of Object.entries(responseInit.headers)) {
res.setHeader(name, value);
}
}
if (typeof res.send === 'function') {
res.send(graphqlResponse);
}
else {
res.end(graphqlResponse);
}
}, (error) => {
if ('HttpQueryError' !== error.name) {
return next(error);
}
if (error.headers) {
for (const [name, value] of Object.entries(error.headers)) {
res.setHeader(name, value);
}
}
res.statusCode = error.statusCode;
if (typeof res.send === 'function') {
res.send(error.message);
}
else {
res.end(error.message);
}
});
};
}
exports.graphqlExpress = graphqlExpress;
//# sourceMappingURL=expressApollo.js.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"expressApollo.js","sourceRoot":"","sources":["../src/expressApollo.ts"],"names":[],"mappings":";;;AACA,2DAK4B;AAY5B,SAAgB,cAAc,CAC5B,OAAuD;IAEvD,IAAI,CAAC,OAAO,EAAE;QACZ,MAAM,IAAI,KAAK,CAAC,iCAAiC,CAAC,CAAC;KACpD;IAED,IAAI,SAAS,CAAC,MAAM,GAAG,CAAC,EAAE;QACxB,MAAM,IAAI,KAAK,CACb,mDAAmD,SAAS,CAAC,MAAM,EAAE,CACtE,CAAC;KACH;IAED,OAAO,CAAC,GAAG,EAAE,GAAG,EAAE,IAAI,EAAQ,EAAE;QAC9B,iCAAY,CAAC,CAAC,GAAG,EAAE,GAAG,CAAC,EAAE;YACvB,MAAM,EAAE,GAAG,CAAC,MAAM;YAClB,OAAO,EAAE,OAAO;YAChB,KAAK,EAAE,GAAG,CAAC,MAAM,KAAK,MAAM,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC,KAAK;YACnD,OAAO,EAAE,6CAAwB,CAAC,GAAG,CAAC;SACvC,CAAC,CAAC,IAAI,CACL,CAAC,EAAE,eAAe,EAAE,YAAY,EAAE,EAAE,EAAE;YACpC,IAAI,YAAY,CAAC,OAAO,EAAE;gBACxB,KAAK,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,YAAY,CAAC,OAAO,CAAC,EAAE;oBAChE,GAAG,CAAC,SAAS,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;iBAC5B;aACF;YAID,IAAI,OAAO,GAAG,CAAC,IAAI,KAAK,UAAU,EAAE;gBAClC,GAAG,CAAC,IAAI,CAAC,eAAe,CAAC,CAAC;aAC3B;iBAAM;gBACL,GAAG,CAAC,GAAG,CAAC,eAAe,CAAC,CAAC;aAC1B;QACH,CAAC,EACD,CAAC,KAAqB,EAAE,EAAE;YACxB,IAAI,gBAAgB,KAAK,KAAK,CAAC,IAAI,EAAE;gBACnC,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC;aACpB;YAED,IAAI,KAAK,CAAC,OAAO,EAAE;gBACjB,KAAK,MAAM,CAAC,IAAI,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,KAAK,CAAC,OAAO,CAAC,EAAE;oBACzD,GAAG,CAAC,SAAS,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC;iBAC5B;aACF;YAED,GAAG,CAAC,UAAU,GAAG,KAAK,CAAC,UAAU,CAAC;YAClC,IAAI,OAAO,GAAG,CAAC,IAAI,KAAK,UAAU,EAAE;gBAGlC,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;aACzB;iBAAM;gBACL,GAAG,CAAC,GAAG,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;aACxB;QACH,CAAC,CACF,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC;AAzDD,wCAyDC"}

7
node_modules/apollo-server-express/dist/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,7 @@
export { GraphQLUpload, GraphQLOptions, GraphQLExtension, Config, gql, ApolloError, toApolloError, SyntaxError, ValidationError, AuthenticationError, ForbiddenError, UserInputError, defaultPlaygroundOptions, PlaygroundConfig, PlaygroundRenderPageOptions, } from 'apollo-server-core';
export * from 'graphql-tools';
export * from 'graphql-subscriptions';
export { ApolloServer, ServerRegistration, GetMiddlewareOptions, ApolloServerExpressConfig, ExpressContext, } from './ApolloServer';
export { CorsOptions } from 'cors';
export { OptionsJson } from 'body-parser';
//# sourceMappingURL=index.d.ts.map

View File

@@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,aAAa,EACb,cAAc,EACd,gBAAgB,EAChB,MAAM,EACN,GAAG,EAEH,WAAW,EACX,aAAa,EACb,WAAW,EACX,eAAe,EACf,mBAAmB,EACnB,cAAc,EACd,cAAc,EAEd,wBAAwB,EACxB,gBAAgB,EAChB,2BAA2B,GAC5B,MAAM,oBAAoB,CAAC;AAE5B,cAAc,eAAe,CAAC;AAC9B,cAAc,uBAAuB,CAAC;AAGtC,OAAO,EACL,YAAY,EACZ,kBAAkB,EAClB,oBAAoB,EACpB,yBAAyB,EACzB,cAAc,GACf,MAAM,gBAAgB,CAAC;AAExB,OAAO,EAAE,WAAW,EAAE,MAAM,MAAM,CAAC;AACnC,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC"}

29
node_modules/apollo-server-express/dist/index.js generated vendored Normal file
View File

@@ -0,0 +1,29 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
for (var p in m) if (p !== "default" && !exports.hasOwnProperty(p)) __createBinding(exports, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
var apollo_server_core_1 = require("apollo-server-core");
Object.defineProperty(exports, "GraphQLUpload", { enumerable: true, get: function () { return apollo_server_core_1.GraphQLUpload; } });
Object.defineProperty(exports, "GraphQLExtension", { enumerable: true, get: function () { return apollo_server_core_1.GraphQLExtension; } });
Object.defineProperty(exports, "gql", { enumerable: true, get: function () { return apollo_server_core_1.gql; } });
Object.defineProperty(exports, "ApolloError", { enumerable: true, get: function () { return apollo_server_core_1.ApolloError; } });
Object.defineProperty(exports, "toApolloError", { enumerable: true, get: function () { return apollo_server_core_1.toApolloError; } });
Object.defineProperty(exports, "SyntaxError", { enumerable: true, get: function () { return apollo_server_core_1.SyntaxError; } });
Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function () { return apollo_server_core_1.ValidationError; } });
Object.defineProperty(exports, "AuthenticationError", { enumerable: true, get: function () { return apollo_server_core_1.AuthenticationError; } });
Object.defineProperty(exports, "ForbiddenError", { enumerable: true, get: function () { return apollo_server_core_1.ForbiddenError; } });
Object.defineProperty(exports, "UserInputError", { enumerable: true, get: function () { return apollo_server_core_1.UserInputError; } });
Object.defineProperty(exports, "defaultPlaygroundOptions", { enumerable: true, get: function () { return apollo_server_core_1.defaultPlaygroundOptions; } });
__exportStar(require("graphql-tools"), exports);
__exportStar(require("graphql-subscriptions"), exports);
var ApolloServer_1 = require("./ApolloServer");
Object.defineProperty(exports, "ApolloServer", { enumerable: true, get: function () { return ApolloServer_1.ApolloServer; } });
//# sourceMappingURL=index.js.map

1
node_modules/apollo-server-express/dist/index.js.map generated vendored Normal file
View File

@@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,yDAkB4B;AAjB1B,mHAAA,aAAa,OAAA;AAEb,sHAAA,gBAAgB,OAAA;AAEhB,yGAAA,GAAG,OAAA;AAEH,iHAAA,WAAW,OAAA;AACX,mHAAA,aAAa,OAAA;AACb,iHAAA,WAAW,OAAA;AACX,qHAAA,eAAe,OAAA;AACf,yHAAA,mBAAmB,OAAA;AACnB,oHAAA,cAAc,OAAA;AACd,oHAAA,cAAc,OAAA;AAEd,8HAAA,wBAAwB,OAAA;AAK1B,gDAA8B;AAC9B,wDAAsC;AAGtC,+CAMwB;AALtB,4GAAA,YAAY,OAAA"}

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) Microsoft Corporation. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE

View File

@@ -0,0 +1,16 @@
# Installation
> `npm install --save @types/body-parser`
# Summary
This package contains type definitions for body-parser (https://github.com/expressjs/body-parser).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/body-parser.
### Additional Details
* Last updated: Mon, 10 Feb 2020 21:19:04 GMT
* Dependencies: [@types/connect](https://npmjs.com/package/@types/connect), [@types/node](https://npmjs.com/package/@types/node)
* Global values: none
# Credits
These definitions were written by Santi Albo (https://github.com/santialbo), Vilic Vane (https://github.com/vilic), Jonathan Häberle (https://github.com/dreampulse), Gevik Babakhani (https://github.com/blendsdk), Tomasz Łaziuk (https://github.com/tlaziuk), Jason Walton (https://github.com/jwalton), and Piotr Błażejewicz (https://github.com/peterblazejewicz).

View File

@@ -0,0 +1,104 @@
// Type definitions for body-parser 1.19
// Project: https://github.com/expressjs/body-parser
// Definitions by: Santi Albo <https://github.com/santialbo>
// Vilic Vane <https://github.com/vilic>
// Jonathan Häberle <https://github.com/dreampulse>
// Gevik Babakhani <https://github.com/blendsdk>
// Tomasz Łaziuk <https://github.com/tlaziuk>
// Jason Walton <https://github.com/jwalton>
// Piotr Błażejewicz <https://github.com/peterblazejewicz>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
import { NextHandleFunction } from 'connect';
import * as http from 'http';
// for docs go to https://github.com/expressjs/body-parser/tree/1.19.0#body-parser
/** @deprecated */
declare function bodyParser(
options?: bodyParser.OptionsJson & bodyParser.OptionsText & bodyParser.OptionsUrlencoded,
): NextHandleFunction;
declare namespace bodyParser {
interface Options {
/** When set to true, then deflated (compressed) bodies will be inflated; when false, deflated bodies are rejected. Defaults to true. */
inflate?: boolean;
/**
* Controls the maximum request body size. If this is a number,
* then the value specifies the number of bytes; if it is a string,
* the value is passed to the bytes library for parsing. Defaults to '100kb'.
*/
limit?: number | string;
/**
* The type option is used to determine what media type the middleware will parse
*/
type?: string | string[] | ((req: http.IncomingMessage) => any);
/**
* The verify option, if supplied, is called as verify(req, res, buf, encoding),
* where buf is a Buffer of the raw request body and encoding is the encoding of the request.
*/
verify?(req: http.IncomingMessage, res: http.ServerResponse, buf: Buffer, encoding: string): void;
}
interface OptionsJson extends Options {
/**
*
* The reviver option is passed directly to JSON.parse as the second argument.
*/
reviver?(key: string, value: any): any;
/**
* When set to `true`, will only accept arrays and objects;
* when `false` will accept anything JSON.parse accepts. Defaults to `true`.
*/
strict?: boolean;
}
interface OptionsText extends Options {
/**
* Specify the default character set for the text content if the charset
* is not specified in the Content-Type header of the request.
* Defaults to `utf-8`.
*/
defaultCharset?: string;
}
interface OptionsUrlencoded extends Options {
/**
* The extended option allows to choose between parsing the URL-encoded data
* with the querystring library (when `false`) or the qs library (when `true`).
*/
extended?: boolean;
/**
* The parameterLimit option controls the maximum number of parameters
* that are allowed in the URL-encoded data. If a request contains more parameters than this value,
* a 413 will be returned to the client. Defaults to 1000.
*/
parameterLimit?: number;
}
/**
* Returns middleware that only parses json and only looks at requests
* where the Content-Type header matches the type option.
*/
function json(options?: OptionsJson): NextHandleFunction;
/**
* Returns middleware that parses all bodies as a Buffer and only looks at requests
* where the Content-Type header matches the type option.
*/
function raw(options?: Options): NextHandleFunction;
/**
* Returns middleware that parses all bodies as a string and only looks at requests
* where the Content-Type header matches the type option.
*/
function text(options?: OptionsText): NextHandleFunction;
/**
* Returns middleware that only parses urlencoded bodies and only looks at requests
* where the Content-Type header matches the type option
*/
function urlencoded(options?: OptionsUrlencoded): NextHandleFunction;
}
export = bodyParser;

View File

@@ -0,0 +1,57 @@
{
"name": "@types/body-parser",
"version": "1.19.0",
"description": "TypeScript definitions for body-parser",
"license": "MIT",
"contributors": [
{
"name": "Santi Albo",
"url": "https://github.com/santialbo",
"githubUsername": "santialbo"
},
{
"name": "Vilic Vane",
"url": "https://github.com/vilic",
"githubUsername": "vilic"
},
{
"name": "Jonathan Häberle",
"url": "https://github.com/dreampulse",
"githubUsername": "dreampulse"
},
{
"name": "Gevik Babakhani",
"url": "https://github.com/blendsdk",
"githubUsername": "blendsdk"
},
{
"name": "Tomasz Łaziuk",
"url": "https://github.com/tlaziuk",
"githubUsername": "tlaziuk"
},
{
"name": "Jason Walton",
"url": "https://github.com/jwalton",
"githubUsername": "jwalton"
},
{
"name": "Piotr Błażejewicz",
"url": "https://github.com/peterblazejewicz",
"githubUsername": "peterblazejewicz"
}
],
"main": "",
"types": "index.d.ts",
"repository": {
"type": "git",
"url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git",
"directory": "types/body-parser"
},
"scripts": {},
"dependencies": {
"@types/connect": "*",
"@types/node": "*"
},
"typesPublisherContentHash": "4257cff3580f6064eb283c690c28aa3a5347cd3cae2a2e208b8f23c61705724a",
"typeScriptVersion": "2.8"
}

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) Microsoft Corporation.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE

View File

@@ -0,0 +1,15 @@
# Installation
> `npm install --save @types/express-serve-static-core`
# Summary
This package contains type definitions for express-serve-static-core (http://expressjs.com).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/express-serve-static-core/v4.
### Additional Details
* Last updated: Wed, 25 Sep 2024 19:19:36 GMT
* Dependencies: [@types/node](https://npmjs.com/package/@types/node), [@types/qs](https://npmjs.com/package/@types/qs), [@types/range-parser](https://npmjs.com/package/@types/range-parser), [@types/send](https://npmjs.com/package/@types/send)
# Credits
These definitions were written by [Boris Yankov](https://github.com/borisyankov), [Satana Charuwichitratana](https://github.com/micksatana), [Jose Luis Leon](https://github.com/JoseLion), [David Stephens](https://github.com/dwrss), and [Shin Ando](https://github.com/andoshin11).

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,50 @@
{
"name": "@types/express-serve-static-core",
"version": "4.19.6",
"description": "TypeScript definitions for express-serve-static-core",
"homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/express-serve-static-core",
"license": "MIT",
"contributors": [
{
"name": "Boris Yankov",
"githubUsername": "borisyankov",
"url": "https://github.com/borisyankov"
},
{
"name": "Satana Charuwichitratana",
"githubUsername": "micksatana",
"url": "https://github.com/micksatana"
},
{
"name": "Jose Luis Leon",
"githubUsername": "JoseLion",
"url": "https://github.com/JoseLion"
},
{
"name": "David Stephens",
"githubUsername": "dwrss",
"url": "https://github.com/dwrss"
},
{
"name": "Shin Ando",
"githubUsername": "andoshin11",
"url": "https://github.com/andoshin11"
}
],
"main": "",
"types": "index.d.ts",
"repository": {
"type": "git",
"url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git",
"directory": "types/express-serve-static-core"
},
"scripts": {},
"dependencies": {
"@types/node": "*",
"@types/qs": "*",
"@types/range-parser": "*",
"@types/send": "*"
},
"typesPublisherContentHash": "a6eae9098d851d3877b61f9dc806634a6174740520432b72c16dc4fdebca21a7",
"typeScriptVersion": "4.8"
}

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) Microsoft Corporation.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE

View File

@@ -0,0 +1,15 @@
# Installation
> `npm install --save @types/express`
# Summary
This package contains type definitions for express (http://expressjs.com).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/express.
### Additional Details
* Last updated: Tue, 07 Nov 2023 03:09:36 GMT
* Dependencies: [@types/body-parser](https://npmjs.com/package/@types/body-parser), [@types/express-serve-static-core](https://npmjs.com/package/@types/express-serve-static-core), [@types/qs](https://npmjs.com/package/@types/qs), [@types/serve-static](https://npmjs.com/package/@types/serve-static)
# Credits
These definitions were written by [Boris Yankov](https://github.com/borisyankov), [China Medical University Hospital](https://github.com/CMUH), [Puneet Arora](https://github.com/puneetar), and [Dylan Frankland](https://github.com/dfrankland).

View File

@@ -0,0 +1,128 @@
/* =================== USAGE ===================
import express = require("express");
var app = express();
=============================================== */
/// <reference types="express-serve-static-core" />
/// <reference types="serve-static" />
import * as bodyParser from "body-parser";
import * as core from "express-serve-static-core";
import * as qs from "qs";
import * as serveStatic from "serve-static";
/**
* Creates an Express application. The express() function is a top-level function exported by the express module.
*/
declare function e(): core.Express;
declare namespace e {
/**
* This is a built-in middleware function in Express. It parses incoming requests with JSON payloads and is based on body-parser.
* @since 4.16.0
*/
var json: typeof bodyParser.json;
/**
* This is a built-in middleware function in Express. It parses incoming requests with Buffer payloads and is based on body-parser.
* @since 4.17.0
*/
var raw: typeof bodyParser.raw;
/**
* This is a built-in middleware function in Express. It parses incoming requests with text payloads and is based on body-parser.
* @since 4.17.0
*/
var text: typeof bodyParser.text;
/**
* These are the exposed prototypes.
*/
var application: Application;
var request: Request;
var response: Response;
/**
* This is a built-in middleware function in Express. It serves static files and is based on serve-static.
*/
var static: serveStatic.RequestHandlerConstructor<Response>;
/**
* This is a built-in middleware function in Express. It parses incoming requests with urlencoded payloads and is based on body-parser.
* @since 4.16.0
*/
var urlencoded: typeof bodyParser.urlencoded;
/**
* This is a built-in middleware function in Express. It parses incoming request query parameters.
*/
export function query(options: qs.IParseOptions | typeof qs.parse): Handler;
export function Router(options?: RouterOptions): core.Router;
interface RouterOptions {
/**
* Enable case sensitivity.
*/
caseSensitive?: boolean | undefined;
/**
* Preserve the req.params values from the parent router.
* If the parent and the child have conflicting param names, the childs value take precedence.
*
* @default false
* @since 4.5.0
*/
mergeParams?: boolean | undefined;
/**
* Enable strict routing.
*/
strict?: boolean | undefined;
}
interface Application extends core.Application {}
interface CookieOptions extends core.CookieOptions {}
interface Errback extends core.Errback {}
interface ErrorRequestHandler<
P = core.ParamsDictionary,
ResBody = any,
ReqBody = any,
ReqQuery = core.Query,
Locals extends Record<string, any> = Record<string, any>,
> extends core.ErrorRequestHandler<P, ResBody, ReqBody, ReqQuery, Locals> {}
interface Express extends core.Express {}
interface Handler extends core.Handler {}
interface IRoute extends core.IRoute {}
interface IRouter extends core.IRouter {}
interface IRouterHandler<T> extends core.IRouterHandler<T> {}
interface IRouterMatcher<T> extends core.IRouterMatcher<T> {}
interface MediaType extends core.MediaType {}
interface NextFunction extends core.NextFunction {}
interface Locals extends core.Locals {}
interface Request<
P = core.ParamsDictionary,
ResBody = any,
ReqBody = any,
ReqQuery = core.Query,
Locals extends Record<string, any> = Record<string, any>,
> extends core.Request<P, ResBody, ReqBody, ReqQuery, Locals> {}
interface RequestHandler<
P = core.ParamsDictionary,
ResBody = any,
ReqBody = any,
ReqQuery = core.Query,
Locals extends Record<string, any> = Record<string, any>,
> extends core.RequestHandler<P, ResBody, ReqBody, ReqQuery, Locals> {}
interface RequestParamHandler extends core.RequestParamHandler {}
interface Response<
ResBody = any,
Locals extends Record<string, any> = Record<string, any>,
> extends core.Response<ResBody, Locals> {}
interface Router extends core.Router {}
interface Send extends core.Send {}
}
export = e;

View File

@@ -0,0 +1,45 @@
{
"name": "@types/express",
"version": "4.17.21",
"description": "TypeScript definitions for express",
"homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/express",
"license": "MIT",
"contributors": [
{
"name": "Boris Yankov",
"githubUsername": "borisyankov",
"url": "https://github.com/borisyankov"
},
{
"name": "China Medical University Hospital",
"githubUsername": "CMUH",
"url": "https://github.com/CMUH"
},
{
"name": "Puneet Arora",
"githubUsername": "puneetar",
"url": "https://github.com/puneetar"
},
{
"name": "Dylan Frankland",
"githubUsername": "dfrankland",
"url": "https://github.com/dfrankland"
}
],
"main": "",
"types": "index.d.ts",
"repository": {
"type": "git",
"url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git",
"directory": "types/express"
},
"scripts": {},
"dependencies": {
"@types/body-parser": "*",
"@types/express-serve-static-core": "^4.17.33",
"@types/qs": "*",
"@types/serve-static": "*"
},
"typesPublisherContentHash": "fa18ce9be07653182e2674f9a13cf8347ffb270031a7a8d22ba0e785bbc16ce4",
"typeScriptVersion": "4.5"
}

55
node_modules/apollo-server-express/package.json generated vendored Normal file
View File

@@ -0,0 +1,55 @@
{
"name": "apollo-server-express",
"version": "2.26.2",
"description": "Production-ready Node.js GraphQL server for Express and Connect",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"repository": {
"type": "git",
"url": "https://github.com/apollographql/apollo-server",
"directory": "packages/apollo-server-express"
},
"keywords": [
"GraphQL",
"Apollo",
"Server",
"Express",
"Connect",
"Javascript"
],
"author": "Apollo <opensource@apollographql.com>",
"license": "MIT",
"bugs": {
"url": "https://github.com/apollographql/apollo-server/issues"
},
"homepage": "https://github.com/apollographql/apollo-server#readme",
"engines": {
"node": ">=6"
},
"dependencies": {
"@apollographql/graphql-playground-html": "1.6.27",
"@types/accepts": "^1.3.5",
"@types/body-parser": "1.19.0",
"@types/cors": "2.8.10",
"@types/express": "^4.17.12",
"@types/express-serve-static-core": "^4.17.21",
"accepts": "^1.3.5",
"apollo-server-core": "^2.26.2",
"apollo-server-types": "^0.10.0",
"body-parser": "^1.18.3",
"cors": "^2.8.5",
"express": "^4.17.1",
"graphql-subscriptions": "^1.0.0",
"graphql-tools": "^4.0.8",
"parseurl": "^1.3.2",
"subscriptions-transport-ws": "^0.9.19",
"type-is": "^1.6.16"
},
"devDependencies": {
"apollo-server-integration-testsuite": "^2.26.2"
},
"peerDependencies": {
"graphql": "^0.12.0 || ^0.13.0 || ^14.0.0 || ^15.0.0"
},
"gitHead": "8fbc66cded6549d5a61433c9fed26775e60e0648"
}

217
node_modules/apollo-server-express/src/ApolloServer.ts generated vendored Normal file
View File

@@ -0,0 +1,217 @@
import express from 'express';
import corsMiddleware from 'cors';
import { json, OptionsJson } from 'body-parser';
import {
renderPlaygroundPage,
RenderPageOptions as PlaygroundRenderPageOptions,
} from '@apollographql/graphql-playground-html';
import {
GraphQLOptions,
FileUploadOptions,
ApolloServerBase,
formatApolloErrors,
processFileUploads,
ContextFunction,
Context,
Config,
} from 'apollo-server-core';
import type { ExecutionParams } from 'subscriptions-transport-ws';
import accepts from 'accepts';
import typeis from 'type-is';
import { graphqlExpress } from './expressApollo';
export { GraphQLOptions, GraphQLExtension } from 'apollo-server-core';
export interface GetMiddlewareOptions {
path?: string;
cors?: corsMiddleware.CorsOptions | corsMiddleware.CorsOptionsDelegate | boolean;
bodyParserConfig?: OptionsJson | boolean;
onHealthCheck?: (req: express.Request) => Promise<any>;
disableHealthCheck?: boolean;
}
export interface ServerRegistration extends GetMiddlewareOptions {
// Note: You can also pass a connect.Server here. If we changed this field to
// `express.Application | connect.Server`, it would be very hard to get the
// app.use calls to typecheck even though they do work properly. Our
// assumption is that very few people use connect with TypeScript (and in fact
// we suspect the only connect users left writing GraphQL apps are Meteor
// users).
app: express.Application;
}
const fileUploadMiddleware = (
uploadsConfig: FileUploadOptions,
server: ApolloServerBase,
) => (
req: express.Request,
res: express.Response,
next: express.NextFunction,
) => {
// Note: we use typeis directly instead of via req.is for connect support.
if (
!server.disableUploads() &&
typeof processFileUploads === 'function' &&
typeis(req, ['multipart/form-data'])
) {
processFileUploads(req, res, uploadsConfig)
.then(body => {
req.body = body;
next();
})
.catch(error => {
if (error.status && error.expose) res.status(error.status);
next(
formatApolloErrors([error], {
formatter: server.requestOptions.formatError,
debug: server.requestOptions.debug,
}),
);
});
} else {
next();
}
};
export interface ExpressContext {
req: express.Request;
res: express.Response;
connection?: ExecutionParams;
}
export interface ApolloServerExpressConfig extends Config {
context?: ContextFunction<ExpressContext, Context> | Context;
}
export class ApolloServer extends ApolloServerBase {
constructor(config: ApolloServerExpressConfig) {
super(config);
}
// This translates the arguments from the middleware into graphQL options It
// provides typings for the integration specific behavior, ideally this would
// be propagated with a generic to the super class
async createGraphQLServerOptions(
req: express.Request,
res: express.Response,
): Promise<GraphQLOptions> {
return super.graphQLServerOptions({ req, res });
}
protected supportsSubscriptions(): boolean {
return true;
}
protected supportsUploads(): boolean {
return true;
}
public applyMiddleware({ app, ...rest }: ServerRegistration) {
app.use(this.getMiddleware(rest));
}
// TODO: While `express` is not Promise-aware, this should become `async` in
// a major release in order to align the API with other integrations (e.g.
// Hapi) which must be `async`.
public getMiddleware({
path,
cors,
bodyParserConfig,
disableHealthCheck,
onHealthCheck,
}: GetMiddlewareOptions = {}): express.Router {
if (!path) path = '/graphql';
// In case the user didn't bother to call and await the `start` method, we
// kick it off in the background (with any errors getting logged
// and also rethrown from graphQLServerOptions during later requests).
this.ensureStarting();
const router = express.Router();
if (!disableHealthCheck) {
router.use('/.well-known/apollo/server-health', (req, res) => {
// Response follows https://tools.ietf.org/html/draft-inadarei-api-health-check-01
res.type('application/health+json');
if (onHealthCheck) {
onHealthCheck(req)
.then(() => {
res.json({ status: 'pass' });
})
.catch(() => {
res.status(503).json({ status: 'fail' });
});
} else {
res.json({ status: 'pass' });
}
});
}
let uploadsMiddleware;
if (this.uploadsConfig && typeof processFileUploads === 'function') {
uploadsMiddleware = fileUploadMiddleware(this.uploadsConfig, this);
}
// XXX multiple paths?
this.graphqlPath = path;
// Note that we don't just pass all of these handlers to a single app.use call
// for 'connect' compatibility.
if (cors === true) {
router.use(path, corsMiddleware<corsMiddleware.CorsRequest>());
} else if (cors !== false) {
router.use(path, corsMiddleware(cors));
}
if (bodyParserConfig === true) {
router.use(path, json());
} else if (bodyParserConfig !== false) {
router.use(path, json(bodyParserConfig));
}
if (uploadsMiddleware) {
router.use(path, uploadsMiddleware);
}
// Note: if you enable playground in production and expect to be able to see your
// schema, you'll need to manually specify `introspection: true` in the
// ApolloServer constructor; by default, the introspection query is only
// enabled in dev.
router.use(path, (req, res, next) => {
if (this.playgroundOptions && req.method === 'GET') {
// perform more expensive content-type check only if necessary
// XXX We could potentially move this logic into the GuiOptions lambda,
// but I don't think it needs any overriding
const accept = accepts(req);
const types = accept.types() as string[];
const prefersHTML =
types.find(
(x: string) => x === 'text/html' || x === 'application/json',
) === 'text/html';
if (prefersHTML) {
const playgroundRenderPageOptions: PlaygroundRenderPageOptions = {
endpoint: req.originalUrl,
subscriptionEndpoint: this.subscriptionsPath,
...this.playgroundOptions,
};
res.setHeader('Content-Type', 'text/html');
const playground = renderPlaygroundPage(playgroundRenderPageOptions);
res.write(playground);
res.end();
return;
}
}
return graphqlExpress(() => this.createGraphQLServerOptions(req, res))(
req,
res,
next,
);
});
return router;
}
}

View File

@@ -0,0 +1,985 @@
import express from 'express';
import http from 'http';
import request from 'request';
import FormData from 'form-data';
import fs from 'fs';
import { createApolloFetch } from 'apollo-fetch';
import { gql, AuthenticationError } from 'apollo-server-core';
import {
ApolloServer,
ApolloServerExpressConfig,
ServerRegistration,
} from '../ApolloServer';
import {
NODE_MAJOR_VERSION,
testApolloServer,
createServerInfo,
} from 'apollo-server-integration-testsuite';
const typeDefs = gql`
type Query {
hello: String
}
`;
const resolvers = {
Query: {
hello: () => 'hi',
},
};
describe('apollo-server-express', () => {
let server;
let httpServer;
testApolloServer(
async (options, suppressStartCall?: boolean) => {
server = new ApolloServer(options);
if (!suppressStartCall) {
await server.start();
}
const app = express();
server.applyMiddleware({ app });
httpServer = await new Promise<http.Server>(resolve => {
const s = app.listen({ port: 0 }, () => resolve(s));
});
return createServerInfo(server, httpServer);
},
async () => {
if (httpServer && httpServer.listening) await httpServer.close();
if (server) await server.stop();
},
);
});
describe('apollo-server-express', () => {
let server: ApolloServer;
let app: express.Application;
let httpServer: http.Server;
async function createServer(
serverOptions: ApolloServerExpressConfig,
options: Partial<ServerRegistration> = {},
) {
server = new ApolloServer({stopOnTerminationSignals: false, ...serverOptions});
app = express();
server.applyMiddleware({ ...options, app });
httpServer = await new Promise<http.Server>(resolve => {
const l = app.listen({ port: 0 }, () => resolve(l));
});
return createServerInfo(server, httpServer);
}
afterEach(async () => {
if (server) await server.stop();
if (httpServer) await httpServer.close();
});
describe('constructor', () => {
it('accepts typeDefs and resolvers', () => {
return createServer({ typeDefs, resolvers });
});
});
describe('applyMiddleware', () => {
it('can be queried', async () => {
const { url: uri } = await createServer({
typeDefs,
resolvers,
});
const apolloFetch = createApolloFetch({ uri });
const result = await apolloFetch({ query: '{hello}' });
expect(result.data).toEqual({ hello: 'hi' });
expect(result.errors).toBeUndefined();
});
// XXX Unclear why this would be something somebody would want (vs enabling
// introspection without graphql-playground, which seems reasonable, eg you
// have your own graphql-playground setup with a custom link)
it('can enable playground separately from introspection during production', async () => {
const INTROSPECTION_QUERY = `
{
__schema {
directives {
name
}
}
}
`;
const { url: uri } = await createServer({
typeDefs,
resolvers,
introspection: false,
});
const apolloFetch = createApolloFetch({ uri });
const result = await apolloFetch({ query: INTROSPECTION_QUERY });
expect(result.errors.length).toEqual(1);
expect(result.errors[0].extensions.code).toEqual(
'GRAPHQL_VALIDATION_FAILED',
);
return new Promise<http.Server>((resolve, reject) => {
request(
{
url: uri,
method: 'GET',
headers: {
accept:
'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
},
},
(error, response, body) => {
if (error) {
reject(error);
} else {
expect(body).toMatch('GraphQLPlayground');
expect(response.statusCode).toEqual(200);
resolve();
}
},
);
});
});
it('renders GraphQL playground by default when browser requests', async () => {
const nodeEnv = process.env.NODE_ENV;
delete process.env.NODE_ENV;
const { url } = await createServer({
typeDefs,
resolvers,
});
return new Promise<http.Server>((resolve, reject) => {
request(
{
url,
method: 'GET',
headers: {
accept:
'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
},
},
(error, response, body) => {
process.env.NODE_ENV = nodeEnv;
if (error) {
reject(error);
} else {
expect(body).toMatch('GraphQLPlayground');
expect(body).not.toMatch('settings');
expect(response.statusCode).toEqual(200);
resolve();
}
},
);
});
});
it('renders GraphQL playground using request original url', async () => {
const samplePath = '/innerSamplePath';
const rewiredServer = new ApolloServer({
typeDefs,
resolvers,
playground: true,
});
const innerApp = express();
rewiredServer.applyMiddleware({ app: innerApp });
const outerApp = express();
outerApp.use(samplePath, innerApp);
const httpRewiredServer = await new Promise<http.Server>(resolve => {
const l = outerApp.listen({ port: 0 }, () => resolve(l));
});
const { url } = createServerInfo(rewiredServer, httpRewiredServer);
const paths = url.split('/');
const rewiredEndpoint = `${samplePath}/${paths.pop()}`;
await new Promise<http.Server>((resolve, reject) => {
request(
{
url: paths.join('/') + rewiredEndpoint,
method: 'GET',
headers: {
accept:
'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
},
},
(error, response, body) => {
if (error) {
reject(error);
} else {
expect(body).toMatch(rewiredEndpoint);
expect(body).not.toMatch('settings');
expect(response.statusCode).toEqual(200);
resolve();
}
},
);
});
await rewiredServer.stop();
await httpRewiredServer.close();
});
const playgroundPartialOptionsTest = async () => {
const defaultQuery = 'query { foo { bar } }';
const endpoint = '/fumanchupacabra';
const { url } = await createServer(
{
typeDefs,
resolvers,
playground: {
// https://github.com/apollographql/graphql-playground/blob/0e452d2005fcd26f10fbdcc4eed3b2e2af935e3a/packages/graphql-playground-html/src/render-playground-page.ts#L16-L24
// must be made partial
settings: {
'editor.theme': 'light',
} as any,
tabs: [
{
query: defaultQuery,
},
{
endpoint,
} as any,
],
},
},
{},
);
return new Promise<http.Server>((resolve, reject) => {
request(
{
url,
method: 'GET',
headers: {
accept:
'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
Folo: 'bar',
},
},
(error, response, body) => {
if (error) {
reject(error);
} else {
expect(body).toMatch('GraphQLPlayground');
expect(body).toMatch(`\"editor.theme\":\"light\"`);
expect(body).toMatch(defaultQuery);
expect(body).toMatch(endpoint);
expect(response.statusCode).toEqual(200);
resolve();
}
},
);
});
};
it('accepts partial GraphQL Playground Options in production', async () => {
const nodeEnv = process.env.NODE_ENV;
process.env.NODE_ENV = 'production';
await playgroundPartialOptionsTest();
process.env.NODE_ENV = nodeEnv;
});
it(
'accepts partial GraphQL Playground Options when an environment is ' +
'not specified',
async () => {
const nodeEnv = process.env.NODE_ENV;
delete process.env.NODE_ENV;
await playgroundPartialOptionsTest();
process.env.NODE_ENV = nodeEnv;
},
);
it('accepts playground options as a boolean', async () => {
const nodeEnv = process.env.NODE_ENV;
delete process.env.NODE_ENV;
const { url } = await createServer(
{
typeDefs,
resolvers,
playground: false,
},
{},
);
return new Promise<http.Server>((resolve, reject) => {
request(
{
url,
method: 'GET',
headers: {
accept:
'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
},
},
(error, response, body) => {
process.env.NODE_ENV = nodeEnv;
if (error) {
reject(error);
} else {
expect(body).not.toMatch('GraphQLPlayground');
expect(response.statusCode).not.toEqual(200);
resolve();
}
},
);
});
});
it('accepts cors configuration', async () => {
const { url: uri } = await createServer(
{
typeDefs,
resolvers,
},
{
cors: { origin: 'apollographql.com' },
},
);
const apolloFetch = createApolloFetch({ uri }).useAfter(
(response, next) => {
expect(
response.response.headers.get('access-control-allow-origin'),
).toEqual('apollographql.com');
next();
},
);
await apolloFetch({ query: '{hello}' });
});
it('accepts body parser configuration', async () => {
const { url: uri } = await createServer(
{
typeDefs,
resolvers,
},
{
bodyParserConfig: { limit: 0 },
},
);
const apolloFetch = createApolloFetch({ uri });
return new Promise((resolve, reject) => {
apolloFetch({ query: '{hello}' })
.then(reject)
.catch(error => {
expect(error.response).toBeDefined();
expect(error.response.status).toEqual(413);
expect(error.toString()).toMatch('Payload Too Large');
resolve();
});
});
});
describe('healthchecks', () => {
afterEach(async () => {
await server.stop();
});
it('creates a healthcheck endpoint', async () => {
const { port } = await createServer({
typeDefs,
resolvers,
});
return new Promise((resolve, reject) => {
request(
{
url: `http://localhost:${port}/.well-known/apollo/server-health`,
method: 'GET',
},
(error, response, body) => {
if (error) {
reject(error);
} else {
expect(body).toEqual(JSON.stringify({ status: 'pass' }));
expect(response.statusCode).toEqual(200);
resolve();
}
},
);
});
});
it('provides a callback for the healthcheck', async () => {
const { port } = await createServer(
{
typeDefs,
resolvers,
},
{
onHealthCheck: async () => {
throw Error("can't connect to DB");
},
},
);
return new Promise((resolve, reject) => {
request(
{
url: `http://localhost:${port}/.well-known/apollo/server-health`,
method: 'GET',
},
(error, response, body) => {
if (error) {
reject(error);
} else {
expect(body).toEqual(JSON.stringify({ status: 'fail' }));
expect(response.statusCode).toEqual(503);
resolve();
}
},
);
});
});
it('can disable the healthCheck', async () => {
const { port } = await createServer(
{
typeDefs,
resolvers,
},
{
disableHealthCheck: true,
},
);
return new Promise((resolve, reject) => {
request(
{
url: `http://localhost:${port}/.well-known/apollo/server-health`,
method: 'GET',
},
(error, response) => {
if (error) {
reject(error);
} else {
expect(response.statusCode).toEqual(404);
resolve();
}
},
);
});
});
});
// NODE: Skip Node.js 6 and 14, but only because `graphql-upload`
// doesn't support them on the version we use.
([6, 14].includes(NODE_MAJOR_VERSION) ? describe.skip : describe)(
'file uploads',
() => {
it('enabled uploads', async () => {
const { port } = await createServer({
typeDefs: gql`
type File {
filename: String!
mimetype: String!
encoding: String!
}
type Query {
uploads: [File]
}
type Mutation {
singleUpload(file: Upload!): File!
}
`,
resolvers: {
Query: {
uploads: () => {},
},
Mutation: {
singleUpload: async (_, args) => {
expect((await args.file).stream).toBeDefined();
return args.file;
},
},
},
});
const body = new FormData();
body.append(
'operations',
JSON.stringify({
query: `
mutation($file: Upload!) {
singleUpload(file: $file) {
filename
encoding
mimetype
}
}
`,
variables: {
file: null,
},
}),
);
body.append('map', JSON.stringify({ 1: ['variables.file'] }));
body.append('1', fs.createReadStream('package.json'));
try {
const resolved = await fetch(`http://localhost:${port}/graphql`, {
method: 'POST',
body: body as any,
});
const text = await resolved.text();
const response = JSON.parse(text);
expect(response.data.singleUpload).toEqual({
filename: 'package.json',
encoding: '7bit',
mimetype: 'application/json',
});
} catch (error) {
// This error began appearing randomly and seems to be a dev dependency bug.
// https://github.com/jaydenseric/apollo-upload-server/blob/18ecdbc7a1f8b69ad51b4affbd986400033303d4/test.js#L39-L42
if (error.code !== 'EPIPE') throw error;
}
});
it('multipart requests work when Upload in schema', async () => {
const { port } = await createServer({
typeDefs: gql`
type Query {
f(f: Upload!): ID
}
`,
});
const body = new FormData();
body.append(
'operations',JSON.stringify({ query: '{__typename}',
}),
);
body.append('map', '{}');
try {
const resolved = await fetch(`http://localhost:${port}/graphql`, {
method: 'POST',
body: body as any,
});
const response = await resolved.json();
expect(response).toEqual({data: {__typename: 'Query'}});
} catch (error) {
// This error began appearing randomly and seems to be a dev dependency bug.
// https://github.com/jaydenseric/apollo-upload-server/blob/18ecdbc7a1f8b69ad51b4affbd986400033303d4/test.js#L39-L42
if (error.code !== 'EPIPE') throw error;
}
});
it('multipart requests work when uploads: true is passed', async () => {
const { port } = await createServer({
typeDefs: gql`
type Query {
f: ID
}
`,
uploads: true,
});
const body = new FormData();
body.append(
'operations',JSON.stringify({ query: '{__typename}',
}),
);
body.append('map', '{}');
try {
const resolved = await fetch(`http://localhost:${port}/graphql`, {
method: 'POST',
body: body as any,
});
const response = await resolved.json();
expect(response).toEqual({data: {__typename: 'Query'}});
} catch (error) {
// This error began appearing randomly and seems to be a dev dependency bug.
// https://github.com/jaydenseric/apollo-upload-server/blob/18ecdbc7a1f8b69ad51b4affbd986400033303d4/test.js#L39-L42
if (error.code !== 'EPIPE') throw error;
}
});
it('multipart requests do not work when uploads unspecified and Upload is not used in the schema', async () => {
const { port } = await createServer({
typeDefs: gql`
type Query {
f: ID
}
`,
});
const body = new FormData();
body.append(
'operations',JSON.stringify({ query: '{__typename}',
}),
);
body.append('map', '{}');
try {
const resolved = await fetch(`http://localhost:${port}/graphql`, {
method: 'POST',
body: body as any,
});
const response = await resolved.text();
expect(response).toEqual("POST body missing. Did you forget use body-parser middleware?");
} catch (error) {
// This error began appearing randomly and seems to be a dev dependency bug.
// https://github.com/jaydenseric/apollo-upload-server/blob/18ecdbc7a1f8b69ad51b4affbd986400033303d4/test.js#L39-L42
if (error.code !== 'EPIPE') throw error;
}
});
},
);
describe('errors', () => {
it('returns thrown context error as a valid graphql result', async () => {
const nodeEnv = process.env.NODE_ENV;
delete process.env.NODE_ENV;
const typeDefs = gql`
type Query {
hello: String
}
`;
const resolvers = {
Query: {
hello: () => {
throw Error('never get here');
},
},
};
const { url: uri } = await createServer({
typeDefs,
resolvers,
context: () => {
throw new AuthenticationError('valid result');
},
});
const apolloFetch = createApolloFetch({ uri });
const result = await apolloFetch({ query: '{hello}' });
expect(result.errors.length).toEqual(1);
expect(result.data).toBeUndefined();
const e = result.errors[0];
expect(e.message).toMatch('valid result');
expect(e.extensions).toBeDefined();
expect(e.extensions.code).toEqual('UNAUTHENTICATED');
expect(e.extensions.exception.stacktrace).toBeDefined();
process.env.NODE_ENV = nodeEnv;
});
it('propogates error codes in dev mode', async () => {
const nodeEnv = process.env.NODE_ENV;
delete process.env.NODE_ENV;
const { url: uri } = await createServer({
typeDefs: gql`
type Query {
error: String
}
`,
resolvers: {
Query: {
error: () => {
throw new AuthenticationError('we the best music');
},
},
},
});
const apolloFetch = createApolloFetch({ uri });
const result = await apolloFetch({ query: `{error}` });
expect(result.data).toBeDefined();
expect(result.data).toEqual({ error: null });
expect(result.errors).toBeDefined();
expect(result.errors.length).toEqual(1);
expect(result.errors[0].extensions.code).toEqual('UNAUTHENTICATED');
expect(result.errors[0].extensions.exception).toBeDefined();
expect(result.errors[0].extensions.exception.stacktrace).toBeDefined();
process.env.NODE_ENV = nodeEnv;
});
it('propogates error codes in production', async () => {
const nodeEnv = process.env.NODE_ENV;
process.env.NODE_ENV = 'production';
const { url: uri } = await createServer({
typeDefs: gql`
type Query {
error: String
}
`,
resolvers: {
Query: {
error: () => {
throw new AuthenticationError('we the best music');
},
},
},
});
const apolloFetch = createApolloFetch({ uri });
const result = await apolloFetch({ query: `{error}` });
expect(result.data).toBeDefined();
expect(result.data).toEqual({ error: null });
expect(result.errors).toBeDefined();
expect(result.errors.length).toEqual(1);
expect(result.errors[0].extensions.code).toEqual('UNAUTHENTICATED');
expect(result.errors[0].extensions.exception).toBeUndefined();
process.env.NODE_ENV = nodeEnv;
});
it('propogates error codes with null response in production', async () => {
const nodeEnv = process.env.NODE_ENV;
process.env.NODE_ENV = 'production';
const { url: uri } = await createServer({
typeDefs: gql`
type Query {
error: String!
}
`,
resolvers: {
Query: {
error: () => {
throw new AuthenticationError('we the best music');
},
},
},
});
const apolloFetch = createApolloFetch({ uri });
const result = await apolloFetch({ query: `{error}` });
expect(result.data).toBeNull();
expect(result.errors).toBeDefined();
expect(result.errors.length).toEqual(1);
expect(result.errors[0].extensions.code).toEqual('UNAUTHENTICATED');
expect(result.errors[0].extensions.exception).toBeUndefined();
process.env.NODE_ENV = nodeEnv;
});
});
});
describe('extensions', () => {
const books = [
{
title: 'H',
author: 'J',
},
];
const typeDefs = gql`
type Book {
title: String
author: String
}
type Cook @cacheControl(maxAge: 200) {
title: String
author: String
}
type Pook @cacheControl(maxAge: 200) {
title: String
books: [Book] @cacheControl(maxAge: 20, scope: PRIVATE)
}
type Query {
books: [Book]
cooks: [Cook]
pooks: [Pook]
}
`;
const resolvers = {
Query: {
books: () => books,
cooks: () => books,
pooks: () => [{ title: 'pook', books }],
},
};
describe('Cache Control Headers', () => {
it('applies cacheControl Headers and strips out extension', async () => {
const { url: uri } = await createServer({ typeDefs, resolvers });
const apolloFetch = createApolloFetch({ uri }).useAfter(
(response, next) => {
expect(response.response.headers.get('cache-control')).toEqual(
'max-age=200, public',
);
next();
},
);
const result = await apolloFetch({
query: `{ cooks { title author } }`,
});
expect(result.data).toEqual({ cooks: books });
expect(result.extensions).toBeUndefined();
});
it('contains no cacheControl Headers and keeps deprecated extension', async () => {
const { url: uri } = await createServer({
typeDefs,
resolvers,
cacheControl: true,
});
const apolloFetch = createApolloFetch({ uri }).useAfter(
(response, next) => {
expect(response.response.headers.get('cache-control')).toBeNull();
next();
},
);
const result = await apolloFetch({
query: `{ cooks { title author } }`,
});
expect(result.data).toEqual({ cooks: books });
expect(result.extensions).toBeDefined();
expect(result.extensions.cacheControl).toBeDefined();
});
it('contains no cacheControl Headers when uncachable', async () => {
const { url: uri } = await createServer({ typeDefs, resolvers });
const apolloFetch = createApolloFetch({ uri }).useAfter(
(response, next) => {
expect(response.response.headers.get('cache-control')).toBeNull();
next();
},
);
const result = await apolloFetch({
query: `{ books { title author } }`,
});
expect(result.data).toEqual({ books });
expect(result.extensions).toBeUndefined();
});
it('contains private cacheControl Headers when scoped', async () => {
const { url: uri } = await createServer({ typeDefs, resolvers });
const apolloFetch = createApolloFetch({ uri }).useAfter(
(response, next) => {
expect(response.response.headers.get('cache-control')).toEqual(
'max-age=20, private',
);
next();
},
);
const result = await apolloFetch({
query: `{ pooks { title books { title author } } }`,
});
expect(result.data).toEqual({
pooks: [{ title: 'pook', books }],
});
expect(result.extensions).toBeUndefined();
});
it('runs when cache-control is false', async () => {
const { url: uri } = await createServer({
typeDefs,
resolvers,
cacheControl: false,
});
const apolloFetch = createApolloFetch({ uri }).useAfter(
(response, next) => {
expect(response.response.headers.get('cache-control')).toBeNull();
next();
},
);
const result = await apolloFetch({
query: `{ pooks { title books { title author } } }`,
});
expect(result.data).toEqual({
pooks: [{ title: 'pook', books }],
});
expect(result.extensions).toBeUndefined();
});
});
describe('Tracing', () => {
const typeDefs = gql`
type Book {
title: String
author: String
}
type Query {
books: [Book]
}
`;
const resolvers = {
Query: {
books: () => books,
},
};
it('applies tracing extension', async () => {
const { url: uri } = await createServer({
typeDefs,
resolvers,
tracing: true,
});
const apolloFetch = createApolloFetch({ uri });
const result = await apolloFetch({
query: `{ books { title author } }`,
});
expect(result.data).toEqual({ books });
expect(result.extensions).toBeDefined();
expect(result.extensions.tracing).toBeDefined();
});
it('applies tracing extension with cache control enabled', async () => {
const { url: uri } = await createServer({
typeDefs,
resolvers,
tracing: true,
cacheControl: true,
});
const apolloFetch = createApolloFetch({ uri });
const result = await apolloFetch({
query: `{ books { title author } }`,
});
expect(result.data).toEqual({ books });
expect(result.extensions).toBeDefined();
expect(result.extensions.tracing).toBeDefined();
});
});
});
});

View File

@@ -0,0 +1,28 @@
import connect from 'connect';
import query from 'qs-middleware';
import { ApolloServer, ApolloServerExpressConfig } from '../ApolloServer';
import testSuite, {
schema as Schema,
CreateAppOptions,
} from 'apollo-server-integration-testsuite';
function createConnectApp(options: CreateAppOptions = {}) {
const app = connect();
// We do require users of ApolloServer with connect to use a query middleware
// first. The alternative is to add a 'isConnect' bool to ServerRegistration
// and make qs-middleware be a dependency of this package. However, we don't
// think many folks use connect outside of Meteor anyway, and anyone using
// connect is probably already using connect-query or qs-middleware.
app.use(query());
const server = new ApolloServer(
(options.graphqlOptions as ApolloServerExpressConfig) || { schema: Schema },
);
// See comment on ServerRegistration.app for its typing.
server.applyMiddleware({ app: app as any });
return app;
}
describe('integration:Connect', () => {
testSuite(createConnectApp);
});

View File

@@ -0,0 +1,156 @@
import express from 'express';
import http, { Server } from 'http';
import { RESTDataSource } from 'apollo-datasource-rest';
import { createApolloFetch } from 'apollo-fetch';
import { ApolloServer } from '../ApolloServer';
import { createServerInfo } from 'apollo-server-integration-testsuite';
import { gql } from '../index';
export class IdAPI extends RESTDataSource {
// Set in subclass
// baseURL = `http://localhost:${restPort}/`;
async getId(id: string) {
return this.get(`id/${id}`);
}
async getStringId(id: string) {
return this.get(`str/${id}`);
}
}
const typeDefs = gql`
type Query {
id: String
stringId: String
}
`;
const resolvers = {
Query: {
id: async (_source, _args, { dataSources }) => {
return (await dataSources.id.getId('hi')).id;
},
stringId: async (_source, _args, { dataSources }) => {
return dataSources.id.getStringId('hi');
},
},
};
let restCalls = 0;
const restAPI = express();
restAPI.use('/id/:id', (req, res) => {
const id = req.params.id;
restCalls++;
res.header('Content-Type', 'application/json');
res.header('Cache-Control', 'max-age=2000, public');
res.write(JSON.stringify({ id }));
res.end();
});
restAPI.use('/str/:id', (req, res) => {
const id = req.params.id;
restCalls++;
res.header('Content-Type', 'text/plain');
res.header('Cache-Control', 'max-age=2000, public');
res.write(id);
res.end();
});
describe('apollo-server-express', () => {
let restServer: Server;
let restUrl: string;
beforeAll(async () => {
restUrl = await new Promise(resolve => {
restServer = restAPI.listen(0, () => {
const { port } = restServer.address();
resolve(`http://localhost:${port}`);
});
});
});
afterAll(async () => {
await restServer.close();
});
let server: ApolloServer;
let httpServer: http.Server;
beforeEach(() => {
restCalls = 0;
});
afterEach(async () => {
await server.stop();
await httpServer.close();
});
it('uses the cache', async () => {
server = new ApolloServer({
typeDefs,
resolvers,
dataSources: () => ({
id: new class extends IdAPI {
baseURL = restUrl;
},
}),
});
const app = express();
server.applyMiddleware({ app });
httpServer = await new Promise<http.Server>(resolve => {
const s: Server = app.listen({ port: 0 }, () => resolve(s));
});
const { url: uri } = createServerInfo(server, httpServer);
const apolloFetch = createApolloFetch({ uri });
const firstResult = await apolloFetch({ query: '{ id }' });
expect(firstResult.errors).toBeUndefined();
expect(firstResult.data).toEqual({ id: 'hi' });
expect(restCalls).toEqual(1);
const secondResult = await apolloFetch({ query: '{ id }' });
expect(secondResult.errors).toBeUndefined();
expect(secondResult.data).toEqual({ id: 'hi' });
expect(restCalls).toEqual(1);
});
it('can cache a string from the backend', async () => {
server = new ApolloServer({
typeDefs,
resolvers,
dataSources: () => ({
id: new class extends IdAPI {
baseURL = restUrl;
},
}),
});
const app = express();
server.applyMiddleware({ app });
httpServer = await new Promise(resolve => {
const s: Server = app.listen({ port: 0 }, () => resolve(s));
});
const { url: uri } = createServerInfo(server, httpServer);
const apolloFetch = createApolloFetch({ uri });
const firstResult = await apolloFetch({ query: '{ id: stringId }' });
expect(firstResult.errors).toBeUndefined();
expect(firstResult.data).toEqual({ id: 'hi' });
expect(restCalls).toEqual(1);
const secondResult = await apolloFetch({ query: '{ id: stringId }' });
expect(secondResult.errors).toBeUndefined();
expect(secondResult.data).toEqual({ id: 'hi' });
expect(restCalls).toEqual(1);
});
});

View File

@@ -0,0 +1,36 @@
import express from 'express';
import { ApolloServer, ApolloServerExpressConfig } from '../ApolloServer';
import { graphqlExpress } from '../expressApollo';
import testSuite, {
schema as Schema,
CreateAppOptions,
} from 'apollo-server-integration-testsuite';
import { GraphQLOptions } from 'apollo-server-core';
function createApp(options: CreateAppOptions = {}) {
const app = express();
const server = new ApolloServer(
(options.graphqlOptions as ApolloServerExpressConfig) || { schema: Schema },
);
server.applyMiddleware({ app });
return app;
}
describe('expressApollo', () => {
it('throws error if called without schema', function() {
expect(() => new ApolloServer(undefined as GraphQLOptions)).toThrow(
'ApolloServer requires options.',
);
});
it('throws error if called with more than one argument', function() {
expect(() => graphqlExpress({ schema: Schema }, 1)).toThrow(
'Apollo Server expects exactly one argument, got 2',
);
});
});
describe('integration:Express', () => {
testSuite(createApp);
});

View File

@@ -0,0 +1,8 @@
{
"extends": "../../../../tsconfig.test.base",
"include": ["**/*"],
"references": [
{ "path": "../../" },
{ "path": "../../../apollo-server-integration-testsuite" },
]
}

View File

@@ -0,0 +1,3 @@
import { graphqlExpress } from './expressApollo';
export const graphqlConnect = graphqlExpress;

View File

@@ -0,0 +1,76 @@
import express from 'express';
import {
GraphQLOptions,
HttpQueryError,
runHttpQuery,
convertNodeHttpToRequest,
} from 'apollo-server-core';
import { ValueOrPromise } from 'apollo-server-types';
export interface ExpressGraphQLOptionsFunction {
(req: express.Request, res: express.Response): ValueOrPromise<GraphQLOptions>;
}
// Design principles:
// - there is just one way allowed: POST request with JSON body. Nothing else.
// - simple, fast and secure
//
export function graphqlExpress(
options: GraphQLOptions | ExpressGraphQLOptionsFunction,
): express.Handler {
if (!options) {
throw new Error('Apollo Server requires options.');
}
if (arguments.length > 1) {
throw new Error(
`Apollo Server expects exactly one argument, got ${arguments.length}`,
);
}
return (req, res, next): void => {
runHttpQuery([req, res], {
method: req.method,
options: options,
query: req.method === 'POST' ? req.body : req.query,
request: convertNodeHttpToRequest(req),
}).then(
({ graphqlResponse, responseInit }) => {
if (responseInit.headers) {
for (const [name, value] of Object.entries(responseInit.headers)) {
res.setHeader(name, value);
}
}
// Using `.send` is a best practice for Express, but we also just use
// `.end` for compatibility with `connect`.
if (typeof res.send === 'function') {
res.send(graphqlResponse);
} else {
res.end(graphqlResponse);
}
},
(error: HttpQueryError) => {
if ('HttpQueryError' !== error.name) {
return next(error);
}
if (error.headers) {
for (const [name, value] of Object.entries(error.headers)) {
res.setHeader(name, value);
}
}
res.statusCode = error.statusCode;
if (typeof res.send === 'function') {
// Using `.send` is a best practice for Express, but we also just use
// `.end` for compatibility with `connect`.
res.send(error.message);
} else {
res.end(error.message);
}
},
);
};
}

34
node_modules/apollo-server-express/src/index.ts generated vendored Normal file
View File

@@ -0,0 +1,34 @@
export {
GraphQLUpload,
GraphQLOptions,
GraphQLExtension,
Config,
gql,
// Errors
ApolloError,
toApolloError,
SyntaxError,
ValidationError,
AuthenticationError,
ForbiddenError,
UserInputError,
// playground
defaultPlaygroundOptions,
PlaygroundConfig,
PlaygroundRenderPageOptions,
} from 'apollo-server-core';
export * from 'graphql-tools';
export * from 'graphql-subscriptions';
// ApolloServer integration.
export {
ApolloServer,
ServerRegistration,
GetMiddlewareOptions,
ApolloServerExpressConfig,
ExpressContext,
} from './ApolloServer';
export { CorsOptions } from 'cors';
export { OptionsJson } from 'body-parser';