initial attempt at core refactor with typescript

This commit is contained in:
Jonas Helfer 2016-06-10 17:05:39 -07:00
parent c3bdbf59ee
commit d19f31331d
40 changed files with 9614 additions and 2391 deletions

View file

@ -1,3 +0,0 @@
{
"presets": ["es2015", "stage-0"]
}

View file

@ -1,14 +0,0 @@
language: node_js
node_js:
- "5.1"
- "4.2"
install:
- npm install -g coveralls
- npm install
script:
- npm test
- coveralls < ./coverage/lcov.info || true # if coveralls doesn't have it covered
# Allow Travis tests to run in containers.
sudo: false

View file

@ -1,17 +1,16 @@
{
"name": "apollo-server",
"version": "0.1.2",
"version": "0.2.0",
"description": "Apollo GraphQL server for Node.js",
"main": "dist/index.js",
"directories": {
"test": "test"
},
"scripts": {
"test": "istanbul cover ./node_modules/mocha/bin/_mocha -- --reporter spec --full-trace test/index.js",
"lint": "eslint .",
"testonly": "mocha test/index.js",
"prepublish": "babel ./src --ignore test --out-dir ./dist",
"postinstall": "npm dedupe"
"compile": "tsc",
"postinstall": "typings install && npm dedupe",
"prepublish": "npm run compile",
"test": "mocha --reporter spec --full-trace test/tests.js"
},
"repository": {
"type": "git",
@ -26,62 +25,24 @@
"Javascript"
],
"author": "Jonas Helfer <jonas@helfer.email>",
"license": "ISC",
"license": "MIT",
"bugs": {
"url": "https://github.com/apollostack/apollo-proxy/issues"
},
"homepage": "https://github.com/apollostack/apollo-proxy#readme",
"dependencies": {
"babel-polyfill": "^6.5.0",
"graphql-tools": "^0.4.2",
"express-widgetizer": "^0.5.2",
"fs": "0.0.2",
"lodash": "^4.10.0",
"node-uuid": "^1.4.7",
"performance-now": "^0.2.0",
"request": "^2.72.0"
"es6-promise": "^3.2.1",
"source-map-support": "^0.4.0"
},
"devDependencies": {
"babel-cli": "^6.6.5",
"babel-core": "6.3.21",
"babel-eslint": "^6.0.0-beta.6",
"babel-loader": "6.2.0",
"babel-preset-es2015": "^6.5.0",
"babel-preset-stage-0": "^6.5.0",
"body-parser": "^1.15.0",
"chai": "^3.5.0",
"dataloader": "^1.1.0",
"eslint": "^2.4.0",
"eslint-config-airbnb": "^6.1.0",
"eslint-plugin-import": "^1.1.0",
"express": "^4.13.4",
"express3": "0.0.0",
"graphql": "^0.5.0",
"graphql": "^0.6.0",
"istanbul": "1.0.0-alpha.2",
"mocha": "^2.3.3",
"multer": "^1.0.3",
"nodemon": "^1.9.1",
"request-promise": "^2.0.1",
"supertest": "^1.0.1",
"supertest-as-promised": "^2.0.2"
"typescript": "^1.8.10",
"typings": "^1.0.4"
},
"peerDependencies": {
"graphql": "^0.5.0"
},
"eslintConfig": {
"parser": "babel-eslint",
"extends": [
"airbnb/base",
"plugin:import/errors"
],
"rules": {
"no-use-before-define": 0,
"arrow-body-style": 0,
"dot-notation": 0,
"no-console": 0
},
"env": {
"mocha": true
}
"graphql": "^0.6.0"
}
}

View file

@ -1,259 +0,0 @@
import {
makeExecutableSchema,
buildSchemaFromTypeDefinitions,
addErrorLoggingToSchema,
addCatchUndefinedToSchema,
addResolveFunctionsToSchema,
addTracingToResolvers,
attachConnectorsToContext,
} from 'graphql-tools';
import { addMockFunctionsToSchema } from 'graphql-tools';
import graphqlHTTP from 'express-widgetizer';
import { GraphQLSchema, formatError } from 'graphql';
// TODO this implementation could use a bit of refactoring.
// it turned from a simple function into something promise-based,
// which means the structure is now quite awkward.
export default function apolloServer(options, ...rest) {
if (!options) {
throw new Error('GraphQL middleware requires options.');
}
if (rest.length > 0) {
throw new Error(`apolloServer expects exactly one argument, got ${rest.length + 1}`);
}
// Resolve the Options to get OptionsData.
return (req, res) => {
let tracerLogger;
// TODO instrument ApolloServer's schema creation as well, so you know how long
// it takes. May be a big waste of time to recreate the schema for every request.
return new Promise(resolve => {
resolve(typeof options === 'function' ? options(req) : options);
}).then(optionsData => {
// Assert that optionsData is in fact an Object.
if (!optionsData || typeof optionsData !== 'object') {
throw new Error(
'GraphQL middleware option function must return an options object.'
);
}
// Assert that schema is required.
if (!optionsData.schema) {
throw new Error(
'GraphQL middleware options must contain a schema.'
);
}
const {
schema, // required
resolvers, // required if mocks is not false and schema is not GraphQLSchema
connectors, // required if mocks is not false and schema is not GraphQLSchema
logger,
tracer,
printErrors,
mocks = false,
allowUndefinedInResolve = true,
pretty, // pass through
graphiql = false, // pass through
validationRules, // pass through
context = {}, // pass through, but add tracer if applicable
rootValue, // pass through
} = optionsData;
// would collide with formatError from graphql otherwise
const formatErrorFn = optionsData.formatError;
// TODO: currently relies on the fact that start and end both exist
// and appear in the correct order and exactly once.
function processInterval(supertype, subtype, tstamp, intervalMap) {
if (subtype === 'start') {
// eslint-disable-next-line no-param-reassign
intervalMap[supertype] = tstamp;
}
if (subtype === 'end') {
// eslint-disable-next-line no-param-reassign
intervalMap[supertype] = tstamp - intervalMap[supertype];
}
}
let executableSchema;
if (mocks) {
// TODO: mocks doesn't yet work with a normal GraphQL schema, but it should!
// have to rewrite these functions
const myMocks = mocks || {};
if (schema instanceof GraphQLSchema) {
executableSchema = schema;
} else {
executableSchema = buildSchemaFromTypeDefinitions(schema);
}
addResolveFunctionsToSchema(executableSchema, resolvers || {});
addMockFunctionsToSchema({
schema: executableSchema,
mocks: myMocks,
preserveResolvers: true,
});
if (connectors) {
attachConnectorsToContext(executableSchema, connectors);
}
} else {
// this is just basics, makeExecutableSchema should catch the rest
// TODO: should be able to provide a GraphQLschema and still use resolvers
// and connectors if you want, but at the moment this is not possible.
if (schema instanceof GraphQLSchema) {
if (logger) {
addErrorLoggingToSchema(schema, logger);
}
if (printErrors) {
addErrorLoggingToSchema(schema, { log: (e) => console.error(e.stack) });
}
if (!allowUndefinedInResolve) {
addCatchUndefinedToSchema(schema);
}
executableSchema = schema;
if (resolvers) {
addResolveFunctionsToSchema(executableSchema, resolvers);
}
} else {
if (!resolvers) {
// TODO: test this error
throw new Error('resolvers is required option if mocks is not provided');
}
executableSchema = makeExecutableSchema({
typeDefs: schema,
resolvers,
connectors,
logger,
allowUndefinedInResolve,
});
if (printErrors) {
addErrorLoggingToSchema(executableSchema, { log: (e) => console.error(e.stack) });
}
}
}
// Tracer-related stuff ------------------------------------------------
tracerLogger = { log: undefined, report: undefined };
if (tracer) {
tracerLogger = tracer.newLoggerInstance();
tracerLogger.log('request.info', {
headers: req.headers,
baseUrl: req.baseUrl,
originalUrl: req.originalUrl,
method: req.method,
httpVersion: req.httpVersion,
remoteAddr: req.connection.remoteAddress,
});
if (context.tracer) {
throw new Error('Property tracer on context already defined, cannot attach Tracer');
} else {
context.tracer = tracerLogger;
}
if (!executableSchema._apolloTracerApplied) {
addTracingToResolvers(executableSchema);
}
}
// TODO: move to proper place, make less fragile ...
// calculate timing information from events
function timings(events) {
const resolverDurations = [];
const intervalMap = {};
// split by event.type = [ , ]
events.forEach(e => {
const [supertype, subtype] = e.type.split('.');
switch (supertype) {
case 'request':
case 'parse':
case 'validation':
case 'execution':
case 'parseBody':
case 'parseParams':
processInterval(supertype, subtype, e.timestamp, intervalMap);
break;
case 'resolver':
if (subtype === 'end') {
resolverDurations.push({
type: 'resolve',
functionName: e.data.functionName,
duration: e.timestamp - events[e.data.startEventId].timestamp,
});
}
break;
default:
console.error(`Unknown event type ${supertype}`);
}
});
const durations = [];
Object.keys(intervalMap).forEach((key) => {
durations.push({
type: key,
functionName: null,
duration: intervalMap[key],
});
});
return durations.concat(resolverDurations);
}
let extensionsFn = function extensionsFn() {
try {
return {
timings: timings(tracerLogger.report().events),
tracer: tracerLogger.report().events.map(e => ({
id: e.id,
type: e.type,
ts: e.timestamp,
data: e.data,
})).filter(x => x.type !== 'initialization'),
};
} catch (e) {
console.error(e);
console.error(e.stack);
}
return {};
};
// XXX ugly way of only passing extensionsFn when tracer is defined.
if (!tracer || req.headers['x-apollo-tracer-extension'] !== 'on') {
extensionsFn = undefined;
}
// end of Tracer related stuff -------------------------------------------
// graphQLHTTPOptions
return {
schema: executableSchema,
pretty,
formatError: formatErrorFn,
validationRules,
context,
rootValue,
graphiql,
logFn: tracerLogger.log,
extensionsFn,
};
}).then((graphqlHTTPOptions) => {
return graphqlHTTP(graphqlHTTPOptions)(req, res);
}).catch(error => {
// express-graphql catches its own errors, this is just for
// errors in Apollo-server.
// XXX we should probably care about formatErrorFn and pretty.
res.status(error.status || 500);
const result = { errors: [error] };
result.errors = result.errors.map(formatError);
res
.set('Content-Type', 'application/json')
.send(JSON.stringify(result));
return result;
}).then(() => {
// send traces to Apollo Tracer
tracerLogger.submit();
});
};
}
export { apolloServer };

25
src/core/runQuery.js Normal file
View file

@ -0,0 +1,25 @@
var graphql_1 = require('graphql');
function runQuery(schema, query, rootValue, context, variables, operationName) {
var documentAST;
// if query is already an AST, don't parse or validate
if (typeof query === 'string') {
// parse
try {
documentAST = graphql_1.parse(query);
}
catch (syntaxError) {
return Promise.resolve({ errors: [syntaxError] });
}
// validate
var validationErrors = graphql_1.validate(schema, documentAST, []);
if (validationErrors.length) {
return Promise.resolve({ errors: validationErrors });
}
}
else {
documentAST = query;
}
// execute
return graphql_1.execute(schema, documentAST, rootValue, context, variables, operationName);
}
exports.runQuery = runQuery;

35
src/core/runQuery.test.ts Normal file
View file

@ -0,0 +1,35 @@
import {
assert,
} from 'chai';
import {
GraphQLSchema,
GraphQLObjectType,
GraphQLString
} from 'graphql';
import { runQuery } from './runQuery';
const QueryType = new GraphQLObjectType({
name: 'QueryType',
fields: {
testString: {
type: GraphQLString,
resolve(){
return 'it works';
},
},
},
});
const Schema = new GraphQLSchema({
query: QueryType,
});
describe('runQuery', () => {
it('returns a response', (done) => {
const query = `{ testString }`;
assert(true);
});
});

49
src/core/runQuery.ts Normal file
View file

@ -0,0 +1,49 @@
import { GraphQLSchema, GraphQLResult, Document } from 'graphql';
import { parse, validate, execute } from 'graphql';
interface gqlResponse {
data?: Object,
errors?: Array<string>,
}
function runQuery(
schema: GraphQLSchema,
query: string | Document,
rootValue?: any,
context?: any,
variables?: { [key: string]: any },
operationName?: string,
//logFunction?: function => void,
) : Promise<GraphQLResult> {
let documentAST: Document;
// if query is already an AST, don't parse or validate
if (typeof query === 'string'){
// parse
try {
documentAST = parse(query);
} catch (syntaxError) {
return Promise.resolve({ errors: [syntaxError] });
}
// validate
const validationErrors = validate(schema, documentAST, []);
if (validationErrors.length) {
return Promise.resolve({ errors: validationErrors })
}
} else {
documentAST = query
}
// execute
return execute(
schema,
documentAST,
rootValue,
context,
variables,
operationName
);
}
export { runQuery };

View file

@ -1,4 +0,0 @@
export {
apolloServer,
} from './apolloServer';

10
src/test/tests.ts Normal file
View file

@ -0,0 +1,10 @@
/* tslint:disable */
// ensure support for promise
import 'es6-promise';
process.env.NODE_ENV = 'test';
declare function require(name: string);
require('source-map-support').install();
import '../core/runQuery.test';

View file

@ -1,7 +0,0 @@
// This file cannot be written with ECMAScript 2015 because it has to load
// the Babel require hook to enable ECMAScript 2015 features!
require('babel-core/register');
require('babel-polyfill');
// The tests, however, can and should be written with ECMAScript 2015.
require('./tests.js');

View file

@ -1,614 +0,0 @@
import { apolloServer } from '../src/apolloServer';
import { MockList } from 'graphql-tools';
import { makeExecutableSchema } from 'graphql-tools';
import { Tracer } from 'graphql-tools';
import { expect } from 'chai';
import express from 'express';
import { GraphQLSchema, GraphQLObjectType, GraphQLString } from 'graphql';
import request from 'supertest-as-promised';
const testSchema = `
type RootQuery {
usecontext: String
useTestConnector: String
species(name: String): String
stuff: String
errorField: String
undefinedField: String
}
schema {
query: RootQuery
}
`;
const testJSSchema = new GraphQLSchema({
query: new GraphQLObjectType({
name: 'RootQuery',
fields: {
usecontext: { type: GraphQLString },
useTestConnector: { type: GraphQLString },
species: { type: GraphQLString, args: { name: { type: GraphQLString } } },
stuff: { type: GraphQLString },
errorField: { type: GraphQLString }
}
})
})
const testResolvers = {
__schema: () => {
return { stuff: 'stuff', species: 'ROOT' };
},
RootQuery: {
usecontext: (r, a, ctx) => {
return ctx.usecontext;
},
useTestConnector: (r, a, ctx) => {
return ctx.connectors.TestConnector.get();
},
species: (root, { name }) => root ? root.species + name : name,
errorField: () => {
throw new Error('throws error');
},
},
};
class TestConnector {
get() {
return 'works';
}
}
const testConnectors = {
TestConnector,
};
const server = apolloServer({
schema: testSchema,
resolvers: testResolvers,
connectors: testConnectors,
context: { usecontext: 'Hi there!' },
});
// XXX this app key is not really a secret. It's here so we can either log it
// or filter it out.
const t1 = new Tracer({ TRACER_APP_KEY: 'BDE05C83-E58F-4837-8D9A-9FB5EA605D2A' });
const serverWithTracer = apolloServer({
schema: testSchema,
resolvers: testResolvers,
connectors: testConnectors,
tracer: t1,
});
const jsSchema = makeExecutableSchema({
typeDefs: testSchema,
resolvers: testResolvers,
connectors: testConnectors,
});
const vanillaServerWithTracer = apolloServer({
schema: jsSchema,
tracer: t1,
});
describe('ApolloServer', () => {
it('can serve a basic request', () => {
const app = express();
app.use('/graphql', server);
const expected = {
stuff: 'stuff',
useTestConnector: 'works',
species: 'ROOTuhu',
usecontext: 'Hi there!'
};
return request(app).get(
'/graphql?query={stuff useTestConnector usecontext species(name: "uhu")}'
).then((res) => {
return expect(res.body.data).to.deep.equal(expected);
});
});
it('can add tracer', () => {
const app = express();
app.use('/graphql', serverWithTracer);
const expected = {
stuff: 'stuff',
useTestConnector: 'works',
species: 'ROOTuhu',
};
return request(app)
.get(
'/graphql?query={stuff useTestConnector species(name: "uhu")}'
)
.set('X-Apollo-Tracer-Extension', 'on')
.then((res) => {
// TODO: this test is silly. actually test the output
expect(res.body.extensions.timings.length).to.equal(9);
return expect(res.body.data).to.deep.equal(expected);
});
});
it('does not return traces unless you ask it to', () => {
const app = express();
app.use('/graphql', serverWithTracer);
const expected = {
stuff: 'stuff',
useTestConnector: 'works',
species: 'ROOTuhu',
};
return request(app)
.get(
'/graphql?query={stuff useTestConnector species(name: "uhu")}'
)
.then((res) => {
// eslint-disable-next-line no-unused-expressions
expect(res.body.extensions).to.be.undefined;
return expect(res.body.data).to.deep.equal(expected);
});
});
it('can add tracer to a graphql-js schema', () => {
const app = express();
app.use('/graphql', vanillaServerWithTracer);
const expected = {
stuff: 'stuff',
useTestConnector: 'works',
species: 'ROOTuhu',
};
return request(app).get(
'/graphql?query={stuff useTestConnector species(name: "uhu")}'
)
.set('X-Apollo-Tracer-Extension', 'on')
.then((res) => {
// TODO: this test is silly. actually test the output
expect(res.body.extensions.timings.length).to.equal(9);
return expect(res.body.data).to.deep.equal(expected);
});
});
it('logs tracer events', () => {
const realSendReport = t1.sendReport;
let interceptedReport;
t1.sendReport = (report) => { interceptedReport = report; };
const app = express();
app.use('/graphql', serverWithTracer);
const expected = {
stuff: 'stuff',
useTestConnector: 'works',
species: 'ROOTuhu',
};
return request(app).get(
'/graphql?query={stuff useTestConnector species(name: "uhu")}'
)
.set('X-Apollo-Tracer-Extension', 'on')
.then((res) => {
// TODO can have race conditions here if executing tests in parallel?
// probably better to set up separate tracer instance for this.
t1.sendReport = realSendReport;
// TODO: this test is silly. actually test the output
expect(res.body.extensions.timings.length).to.equal(9);
expect(interceptedReport.events.length).to.equal(25);
return expect(res.body.data).to.deep.equal(expected);
});
});
it('throws an error if schema is shorthand and resolvers not defined', () => {
const app = express();
const verySadServer = apolloServer({
schema: testSchema,
});
app.use('/graphql', verySadServer);
return request(app).get(
'/graphql?query={stuff}'
).then((res) => {
expect(res.status).to.equal(500);
return expect(res.error.text).to.equal(
'{"errors":[{"message":"resolvers is required option if mocks is not provided"}]}'
);
});
});
it('will append resolvers to a js schema', () => {
const app = express();
const jsServer = apolloServer({
schema: testJSSchema,
resolvers: testResolvers
});
app.use('/graphql', jsServer);
return request(app).get(
'/graphql?query={stuff useTestConnector species(name: "uhu")}'
).then((res) => {
return expect(res.body.data.species).to.equal("uhu");
});
});
it('will append resolvers to a js schema when mocked', () => {
const app = express();
const jsServer = apolloServer({
schema: testJSSchema,
resolvers: testResolvers,
mocks: {
RootQuery: () => ({
stuff: () => 'stuffs',
useTestConnector: () => 'utc',
species: 'rawr',
}),
}
});
app.use('/graphql', jsServer);
return request(app).get(
'/graphql?query={stuff useTestConnector species(name: "uhu")}'
).then((res) => {
return expect(res.body.data.species).to.equal("uhu");
});
});
it('can mock a schema', () => {
const app = express();
const mockServer = apolloServer({
schema: testSchema,
mocks: {
RootQuery: () => ({
stuff: () => 'stuffs',
useTestConnector: () => 'utc',
species: 'rawr',
}),
},
});
app.use('/graphql', mockServer);
const expected = {
stuff: 'stuffs',
useTestConnector: 'utc',
species: 'rawr',
};
return request(app).get(
'/graphql?query={stuff useTestConnector species(name: "uhu")}'
).then((res) => {
return expect(res.body.data).to.deep.equal(expected);
});
});
it('can mock a schema and use partially implemented resolvers', () => {
const app = express();
const mockServer = apolloServer({
schema: `
type Query {
mocked: String
resolved(name: String): String
usecontext: String
useTestConnector: String
}
schema {
query: Query
}
`,
context: {
usecontext: 'Hi there!',
},
connectors: testConnectors,
mocks: {
String: () => 'Mocked fallback',
},
resolvers: {
Query: {
resolved(root, { name }) {
return `Hello, ${name}!`;
},
usecontext(root, args, ctx) {
return ctx.usecontext;
},
useTestConnector: (r, a, ctx) => {
return ctx.connectors.TestConnector.get();
},
},
},
});
app.use('/graphql', mockServer);
const expected = {
mocked: 'Mocked fallback',
resolved: 'Hello, world!',
usecontext: 'Hi there!',
useTestConnector: 'works',
};
return request(app).get(
'/graphql?query={mocked usecontext useTestConnector resolved(name: "world")}'
).then((res) => {
return expect(res.body.data).to.deep.equal(expected);
});
});
it('can mock a schema with unions', () => {
const app = express();
const schema = `
enum SomeEnum {
X
Y
Z
}
type A {
a: SomeEnum!
}
type B {
b: Int!
}
union C = A | B
type Query {
someCs: [C]
}
schema {
query: Query
}
`;
const mockServer = apolloServer({
schema,
resolvers: {
C: {
__resolveType(data, ctx, info) {
return info.schema.getType(data.typename);
},
},
},
mocks: {
Int: () => 10,
SomeEnum: () => 'X',
Query: () => ({
someCs: () => new MockList(40),
}),
},
});
app.use('/graphql', mockServer);
return request(app).get(
'/graphql?query={someCs {... on A {a} ... on B {b}}}'
).then((res) => {
const someCs = res.body.data.someCs;
expect(someCs).to.include({a: 'X'});
return expect(someCs).to.include({b: 10});
});
});
it('can log errors', () => {
const app = express();
let lastError;
const loggy = { log: (e) => { lastError = e.originalMessage; } };
const logServer = apolloServer({
schema: testSchema,
resolvers: testResolvers,
connectors: testConnectors,
logger: loggy,
});
app.use('/graphql', logServer);
return request(app).get(
'/graphql?query={errorField}'
).then(() => {
return expect(lastError).to.equal('throws error');
});
});
it('can log errors with a graphQL-JS schema', () => {
const app = express();
let lastError;
const loggy = { log: (e) => { lastError = e.originalMessage; } };
const jsSchema = makeExecutableSchema({
typeDefs: testSchema,
resolvers: testResolvers,
connectors: testConnectors,
});
const logServer = apolloServer({
schema: jsSchema,
logger: loggy,
});
app.use('/graphql', logServer);
return request(app).get(
'/graphql?query={errorField}'
).then(() => {
return expect(lastError).to.equal('throws error');
});
});
it('can forbid undefined errors', () => {
const app = express();
let lastError;
const loggy = { log: (e) => { lastError = e.originalMessage; } };
const logServer = apolloServer({
schema: testSchema,
resolvers: testResolvers,
connectors: testConnectors,
logger: loggy,
allowUndefinedInResolve: false,
});
app.use('/graphql', logServer);
return request(app).get(
'/graphql?query={undefinedField}'
).then(() => {
return expect(lastError).to.equal(
'Resolve function for "RootQuery.undefinedField" returned undefined'
);
});
});
it('can forbid undefined with a graphQL-JS schema', () => {
const app = express();
let lastError;
const loggy = { log: (e) => { lastError = e.originalMessage; } };
const jsSchema = makeExecutableSchema({
typeDefs: testSchema,
resolvers: testResolvers,
connectors: testConnectors,
});
const logServer = apolloServer({
schema: jsSchema,
allowUndefinedInResolve: false,
logger: loggy,
});
app.use('/graphql', logServer);
return request(app).get(
'/graphql?query={undefinedField}'
).then(() => {
return expect(lastError).to.equal(
'Resolve function for "RootQuery.undefinedField" returned undefined'
);
});
});
it('can print errors for you with a shorthand schema', () => {
const app = express();
let lastError;
const realConsoleError = console.error;
console.error = (e) => { lastError = e; };
const printServer = apolloServer({
schema: testSchema,
resolvers: testResolvers,
connectors: testConnectors,
allowUndefinedInResolve: false,
printErrors: true,
});
app.use('/graphql', printServer);
return request(app).get(
'/graphql?query={undefinedField}'
).then(() => {
return expect(lastError).to.match(/Error/);
}).finally(() => {
console.error = realConsoleError;
});
});
it('can print errors for you with a graphQL-JS schema', () => {
const app = express();
let lastError;
const realConsoleError = console.error;
console.error = (e) => { lastError = e; };
const jsSchema = makeExecutableSchema({
typeDefs: testSchema,
resolvers: testResolvers,
connectors: testConnectors,
});
const logServer = apolloServer({
schema: jsSchema,
allowUndefinedInResolve: false,
printErrors: true,
});
app.use('/graphql', logServer);
return request(app).get(
'/graphql?query={undefinedField}'
).then(() => {
return expect(lastError).to.match(/Error/);
}).finally(() => {
console.error = realConsoleError;
});
});
it('can forbid undefined with a graphQL-JS schema', () => {
const app = express();
let lastError;
const loggy = { log: (e) => { lastError = e.originalMessage; } };
const jsSchema = makeExecutableSchema({
typeDefs: testSchema,
resolvers: testResolvers,
connectors: testConnectors,
});
const logServer = apolloServer({
schema: jsSchema,
allowUndefinedInResolve: false,
logger: loggy,
});
app.use('/graphql', logServer);
return request(app).get(
'/graphql?query={undefinedField}'
).then(() => {
return expect(lastError).to.equal(
'Resolve function for "RootQuery.undefinedField" returned undefined'
);
});
});
// TODO: test wrong arguments error messages
it('throws an error if you call it with more than one arg', () => {
return expect(() => apolloServer(1, 2)).to.throw(
'apolloServer expects exactly one argument, got 2'
);
});
// express-graphql tests:
describe('(express-grapqhl) Useful errors when incorrectly used', () => {
it('requires an option factory function', () => {
expect(() => {
apolloServer();
}).to.throw(
'GraphQL middleware requires options.'
);
});
it('requires option factory function to return object', async () => {
var app = express();
app.use('/graphql', apolloServer(() => null));
var caughtError;
var response;
try {
response = await request(app).get('/graphql?query={test}');
} catch (error) {
caughtError = error;
}
expect(response.status).to.equal(500);
expect(JSON.parse(response.error.text)).to.deep.equal({
errors: [
{ message:
'GraphQL middleware option function must return an options object.' }
]
});
});
it('requires option factory function to return object or promise of object', async () => {
var app = express();
app.use('/graphql', apolloServer(() => Promise.resolve(null)));
var caughtError;
var response;
try {
response = await request(app).get('/graphql?query={test}');
} catch (error) {
caughtError = error;
}
expect(response.status).to.equal(500);
expect(JSON.parse(response.error.text)).to.deep.equal({
errors: [
{ message:
'GraphQL middleware option function must return an options object.' }
]
});
});
it('requires option factory function to return object with schema', async () => {
var app = express();
app.use('/graphql', apolloServer(() => ({})));
var caughtError;
var response;
try {
response = await request(app).get('/graphql?query={test}');
} catch (error) {
caughtError = error;
}
expect(response.status).to.equal(500);
expect(JSON.parse(response.error.text)).to.deep.equal({
errors: [
{ message: 'GraphQL middleware options must contain a schema.' }
]
});
});
it('requires option factory function to return object or promise of object with schema', async () => {
var app = express();
app.use('/graphql', apolloServer(() => Promise.resolve({})));
var caughtError;
var response;
try {
response = await request(app).get('/graphql?query={test}');
} catch (error) {
caughtError = error;
}
expect(response.status).to.equal(500);
expect(JSON.parse(response.error.text)).to.deep.equal({
errors: [
{ message: 'GraphQL middleware options must contain a schema.' }
]
});
});
});
});

File diff suppressed because it is too large Load diff

View file

@ -1,2 +0,0 @@
import './testApolloServer';
import './testApolloServerHTTP';

20
tsconfig.json Normal file
View file

@ -0,0 +1,20 @@
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"declaration": true,
"noImplicitAny": false,
"rootDir": ".",
"outDir": "dist",
"allowSyntheticDefaultImports": true,
"pretty": true,
"removeComments": true
},
"files": [
"typings/main.d.ts",
"src/core/runQuery.ts",
"src/test/tests.ts"
]
}

16
typings.json Normal file
View file

@ -0,0 +1,16 @@
{
"dependencies": {
"graphql": "github:nitintutlani/typed-graphql"
},
"globalDependencies": {
"body-parser": "registry:dt/body-parser#0.0.0+20160317120654",
"express": "registry:dt/express#4.0.0+20160317120654",
"express-serve-static-core": "registry:dt/express-serve-static-core#0.0.0+20160322035842",
"hapi": "registry:dt/hapi#13.0.0+20160521152637",
"koa": "registry:dt/koa#2.0.0+20160317120654",
"mime": "registry:dt/mime#0.0.0+20160316155526",
"mocha": "registry:dt/mocha#2.2.5+20160317120654",
"node": "registry:dt/node#6.0.0+20160524002506",
"serve-static": "registry:dt/serve-static#0.0.0+20160501131543"
}
}

1
typings/browser.d.ts vendored Normal file
View file

@ -0,0 +1 @@
/// <reference path="browser/definitions/graphql/index.d.ts" />

View file

@ -0,0 +1,955 @@
// Generated by typings
// Source: https://raw.githubusercontent.com/nitintutlani/typed-graphql/master/graphql.d.ts
declare module '~graphql/graphql' {
// graphql.js
export function graphql(
schema: GraphQLSchema,
requestString: string,
rootValue?: any,
contextValue?: any,
variableValues?: { [key: string]: any },
operationName?: string
): Promise<GraphQLResult>;
interface GraphQLResult {
data?: any;
errors?: Array<GraphQLError>;
}
// error/*.js
class GraphQLError extends Error {
constructor(
message: string,
nodes?: Array<any>,
stack?: string,
source?: Source,
positions?: Array<number>
);
}
export function formatError(error: GraphQLError): GraphQLFormattedError;
interface GraphQLFormattedError {
message: string,
locations: Array<GraphQLErrorLocation>
}
interface GraphQLErrorLocation {
line: number,
column: number
}
function locatedError(originalError: Error, nodes: Array<any>): GraphQLError;
function syntaxError(source: Source, position: number, description: string): GraphQLError;
// execution/*.js
interface ExecutionContext {
schema: GraphQLSchema;
fragments: {[key: string]: FragmentDefinition};
rootValue: any;
operation: OperationDefinition;
variableValues: {[key: string]: any};
errors: Array<GraphQLError>;
}
interface ExecutionResult {
data: any;
errors?: Array<GraphQLError>;
}
function execute(
schema: GraphQLSchema,
documentAST: Document,
rootValue?: any,
contextValue?: any,
variableValues?: {[key: string]: any},
operationName?: string
): Promise<ExecutionResult>;
function getVariableValues(
schema: GraphQLSchema,
definitionASTs: Array<VariableDefinition>,
inputs: { [key: string]: any }
): { [key: string]: any };
function getArgumentValues(
argDefs: Array<GraphQLArgument>,
argASTs: Array<Argument>,
variableValues: { [key: string]: any }
): { [key: string]: any };
// validation/*.js
function validate(
schema: GraphQLSchema,
ast: Document,
rules?: Array<any>
): Array<GraphQLError>;
// jsutils/*.js
function find<T>(list: Array<T>, predicate: (item: T) => boolean): T;
function invariant(condition: any, message: string): void;
function isNullish(value: any): boolean;
function keyMap<T>(
list: Array<T>,
keyFn: (item: T) => string
): {[key: string]: T};
function keyValMap<T, V>(
list: Array<T>,
keyFn: (item: T) => string,
valFn: (item: T) => V
): {[key: string]: V}
// language/ast.js
interface Location {
start: number;
end: number;
source?: Source
}
type Node = Name
| Document
| OperationDefinition
| VariableDefinition
| Variable
| SelectionSet
| Field
| Argument
| FragmentSpread
| InlineFragment
| FragmentDefinition
| IntValue
| FloatValue
| StringValue
| BooleanValue
| EnumValue
| ListValue
| ObjectValue
| ObjectField
| Directive
| ListType
| NonNullType
| ObjectTypeDefinition
| FieldDefinition
| InputValueDefinition
| InterfaceTypeDefinition
| UnionTypeDefinition
| ScalarTypeDefinition
| EnumTypeDefinition
| EnumValueDefinition
| InputObjectTypeDefinition
| TypeExtensionDefinition;
interface Name {
kind: string;
loc?: Location;
value: string;
}
interface Document {
kind: string;
loc?: Location;
definitions: Array<Definition>;
}
type Definition = OperationDefinition
| FragmentDefinition
| TypeDefinition;
interface OperationDefinition {
kind: string;
loc?: Location;
// Note: subscription is an experimental non-spec addition.
operation: string;
name?: Name;
variableDefinitions?: Array<VariableDefinition>;
directives?: Array<Directive>;
selectionSet: SelectionSet;
}
interface VariableDefinition {
kind: string;
loc?: Location;
variable: Variable;
type: Type;
defaultValue?: Value;
}
interface Variable {
kind: string;
loc?: Location;
name: Name;
}
interface SelectionSet {
kind: string;
loc?: Location;
selections: Array<Selection>;
}
type Selection = Field
| FragmentSpread
| InlineFragment;
interface Field {
kind: string;
loc?: Location;
alias?: Name;
name: Name;
arguments?: Array<Argument>;
directives?: Array<Directive>;
selectionSet?: SelectionSet;
}
interface Argument {
kind: string;
loc?: Location;
name: Name;
value: Value;
}
// Fragments
interface FragmentSpread {
kind: string;
loc?: Location;
name: Name;
directives?: Array<Directive>;
}
interface InlineFragment {
kind: string;
loc?: Location;
typeCondition?: NamedType;
directives?: Array<Directive>;
selectionSet: SelectionSet;
}
interface FragmentDefinition {
kind: string;
loc?: Location;
name: Name;
typeCondition: NamedType;
directives?: Array<Directive>;
selectionSet: SelectionSet;
}
// Values
type Value = Variable
| IntValue
| FloatValue
| StringValue
| BooleanValue
| EnumValue
| ListValue
| ObjectValue;
interface IntValue {
kind: string;
loc?: Location;
value: string;
}
interface FloatValue {
kind: string;
loc?: Location;
value: string;
}
interface StringValue {
kind: string;
loc?: Location;
value: string;
}
interface BooleanValue {
kind: string;
loc?: Location;
value: boolean;
}
interface EnumValue {
kind: string;
loc?: Location;
value: string;
}
interface ListValue {
kind: string;
loc?: Location;
values: Array<Value>;
}
interface ObjectValue {
kind: string;
loc?: Location;
fields: Array<ObjectField>;
}
interface ObjectField {
kind: string;
loc?: Location;
name: Name;
value: Value;
}
// Directives
interface Directive {
kind: string;
loc?: Location;
name: Name;
arguments?: Array<Argument>;
}
// Type Reference
type Type = NamedType
| ListType
| NonNullType;
interface NamedType {
kind: string;
loc?: Location;
name: Name;
}
interface ListType {
kind: string;
loc?: Location;
type: Type;
}
interface NonNullType {
kind: string;
loc?: Location;
type: NamedType | ListType;
}
// Type Definition
type TypeDefinition = ObjectTypeDefinition
| InterfaceTypeDefinition
| UnionTypeDefinition
| ScalarTypeDefinition
| EnumTypeDefinition
| InputObjectTypeDefinition
| TypeExtensionDefinition;
interface ObjectTypeDefinition {
kind: string;
loc?: Location;
name: Name;
interfaces?: Array<NamedType>;
fields: Array<FieldDefinition>;
}
interface FieldDefinition {
kind: string;
loc?: Location;
name: Name;
arguments: Array<InputValueDefinition>;
type: Type;
}
interface InputValueDefinition {
kind: string;
loc?: Location;
name: Name;
type: Type;
defaultValue?: Value;
}
interface InterfaceTypeDefinition {
kind: string;
loc?: Location;
name: Name;
fields: Array<FieldDefinition>;
}
interface UnionTypeDefinition {
kind: string;
loc?: Location;
name: Name;
types: Array<NamedType>;
}
interface ScalarTypeDefinition {
kind: string;
loc?: Location;
name: Name;
}
interface EnumTypeDefinition {
kind: string;
loc?: Location;
name: Name;
values: Array<EnumValueDefinition>;
}
interface EnumValueDefinition {
kind: string;
loc?: Location;
name: Name;
}
interface InputObjectTypeDefinition {
kind: string;
loc?: Location;
name: Name;
fields: Array<InputValueDefinition>;
}
interface TypeExtensionDefinition {
kind: string;
loc?: Location;
definition: ObjectTypeDefinition;
}
// language/kinds.js
const NAME: string;
// Document
const DOCUMENT: string;
const OPERATION_DEFINITION: string;
const VARIABLE_DEFINITION: string;
const VARIABLE: string;
const SELECTION_SET: string;
const FIELD: string;
const ARGUMENT: string;
// Fragments
const FRAGMENT_SPREAD: string;
const INLINE_FRAGMENT: string;
const FRAGMENT_DEFINITION: string;
// Values
const INT: string;
const FLOAT: string;
const STRING: string;
const BOOLEAN: string;
const ENUM: string;
const LIST: string;
const OBJECT: string;
const OBJECT_FIELD: string;
// Directives
const DIRECTIVE: string;
// Types
const NAMED_TYPE: string;
const LIST_TYPE: string;
const NON_NULL_TYPE: string;
// Type Definitions
const OBJECT_TYPE_DEFINITION: string;
const FIELD_DEFINITION: string;
const INPUT_VALUE_DEFINITION: string;
const INTERFACE_TYPE_DEFINITION: string;
const UNION_TYPE_DEFINITION: string;
const SCALAR_TYPE_DEFINITION: string;
const ENUM_TYPE_DEFINITION: string;
const ENUM_VALUE_DEFINITION: string;
const INPUT_OBJECT_TYPE_DEFINITION: string;
const TYPE_EXTENSION_DEFINITION: string;
// language/lexer.js
interface Token {
kind: number;
start: number;
end: number;
value: string;
}
type Lexer = (resetPosition?: number) => Token;
function lex(source: Source): Lexer;
type TokenKind = {[key: string]: number};
function getTokenDesc(token: Token): string;
function getTokenKindDesc(kind: number): string;
// language/location.js
interface SourceLocation {
line: number;
column: number;
}
function getLocation(source: Source, position: number): SourceLocation;
// language/parser.js
interface ParseOptions {
noLocation?: boolean,
noSource?: boolean,
}
function parse(
source: Source | string,
options?: ParseOptions
): Document;
function parseValue(
source: Source | string,
options?: ParseOptions
): Value;
function parseConstValue(parser: any): Value;
function parseType(parser: any): Type;
function parseNamedType(parser: any): NamedType;
// language/printer.js
function print(ast: any): string;
// language/source.js
class Source {
body: string;
name: string;
constructor(body: string, name?: string);
}
// language/visitor.js
interface QueryDocumentKeys {
Name: any[];
Document: string[];
OperationDefinition: string[];
VariableDefinition: string[];
Variable: string[];
SelectionSet: string[];
Field: string[];
Argument: string[];
FragmentSpread: string[];
InlineFragment: string[];
FragmentDefinition: string[];
IntValue: number[];
FloatValue: number[];
StringValue: string[];
BooleanValue: boolean[];
EnumValue: any[];
ListValue: string[];
ObjectValue: string[];
ObjectField: string[];
Directive: string[];
NamedType: string[];
ListType: string[];
NonNullType: string[];
ObjectTypeDefinition: string[];
FieldDefinition: string[];
InputValueDefinition: string[];
InterfaceTypeDefinition: string[];
UnionTypeDefinition: string[];
ScalarTypeDefinition: string[];
EnumTypeDefinition: string[];
EnumValueDefinition: string[];
InputObjectTypeDefinition: string[];
TypeExtensionDefinition: string[];
}
const BREAK: Object;
function visit(root: any, visitor: any, keyMap: any): any;
function visitInParallel(visitors: any): any;
function visitWithTypeInfo(typeInfo: any, visitor: any): any;
// type/definition.js
type GraphQLType =
GraphQLScalarType |
GraphQLObjectType |
GraphQLInterfaceType |
GraphQLUnionType |
GraphQLEnumType |
GraphQLInputObjectType |
GraphQLList |
GraphQLNonNull;
function isType(type: any): boolean;
type GraphQLInputType =
GraphQLScalarType |
GraphQLEnumType |
GraphQLInputObjectType |
GraphQLList |
GraphQLNonNull;
function isInputType(type: GraphQLType): boolean;
type GraphQLOutputType =
GraphQLScalarType |
GraphQLObjectType |
GraphQLInterfaceType |
GraphQLUnionType |
GraphQLEnumType |
GraphQLList |
GraphQLNonNull;
function isOutputType(type: GraphQLType): boolean;
type GraphQLLeafType =
GraphQLScalarType |
GraphQLEnumType;
function isLeafType(type: GraphQLType): boolean;
type GraphQLCompositeType =
GraphQLObjectType |
GraphQLInterfaceType |
GraphQLUnionType;
function isCompositeType(type: GraphQLType): boolean;
type GraphQLAbstractType =
GraphQLInterfaceType |
GraphQLUnionType;
function isAbstractType(type: GraphQLType): boolean;
type GraphQLNullableType =
GraphQLScalarType |
GraphQLObjectType |
GraphQLInterfaceType |
GraphQLUnionType |
GraphQLEnumType |
GraphQLInputObjectType |
GraphQLList;
function getNullableType(type: GraphQLType): GraphQLNullableType;
type GraphQLNamedType =
GraphQLScalarType |
GraphQLObjectType |
GraphQLInterfaceType |
GraphQLUnionType |
GraphQLEnumType |
GraphQLInputObjectType;
function getNamedType(type: GraphQLType): GraphQLNamedType;
export class GraphQLScalarType {
constructor(config: GraphQLScalarTypeConfig);
serialize(value: any): any;
parseValue(value: any): any;
parseLiteral(valueAST: Value): any;
toString(): string;
}
interface GraphQLScalarTypeConfig {
name: string;
description?: string;
serialize: (value: any) => any;
parseValue?: (value: any) => any;
parseLiteral?: (valueAST: Value) => any;
}
export class GraphQLObjectType {
constructor(config: GraphQLObjectTypeConfig);
getFields(): GraphQLFieldDefinitionMap;
getInterfaces(): Array<GraphQLInterfaceType>;
toString(): string;
}
interface GraphQLObjectTypeConfig {
name: string;
interfaces?: GraphQLInterfacesThunk | Array<GraphQLInterfaceType>;
fields: GraphQLFieldConfigMapThunk | GraphQLFieldConfigMap;
isTypeOf?: (value: any, info?: GraphQLResolveInfo) => boolean;
description?: string
}
type GraphQLInterfacesThunk = () => Array<GraphQLInterfaceType>;
type GraphQLFieldConfigMapThunk = () => GraphQLFieldConfigMap;
type GraphQLFieldResolveFn = (
source?: any,
args?: { [argName: string]: any },
context?: any,
info?: GraphQLResolveInfo
) => any;
interface GraphQLResolveInfo {
fieldName: string,
fieldASTs: Array<Field>,
returnType: GraphQLOutputType,
parentType: GraphQLCompositeType,
schema: GraphQLSchema,
fragments: { [fragmentName: string]: FragmentDefinition },
rootValue: any,
operation: OperationDefinition,
variableValues: { [variableName: string]: any },
}
interface GraphQLFieldConfig {
type: GraphQLOutputType;
args?: GraphQLFieldConfigArgumentMap;
resolve?: GraphQLFieldResolveFn;
deprecationReason?: string;
description?: string;
}
interface GraphQLFieldConfigArgumentMap {
[argName: string]: GraphQLArgumentConfig;
}
interface GraphQLArgumentConfig {
type: GraphQLInputType;
defaultValue?: any;
description?: string;
}
interface GraphQLFieldConfigMap {
[fieldName: string]: GraphQLFieldConfig;
}
interface GraphQLFieldDefinition {
name: string;
description: string;
type: GraphQLOutputType;
args: Array<GraphQLArgument>;
resolve?: GraphQLFieldResolveFn;
deprecationReason?: string;
}
interface GraphQLArgument {
name: string;
type: GraphQLInputType;
defaultValue?: any;
description?: string;
}
interface GraphQLFieldDefinitionMap {
[fieldName: string]: GraphQLFieldDefinition;
}
export class GraphQLInterfaceType {
name: string;
description: string;
resolveType: (value: any, info?: GraphQLResolveInfo) => GraphQLObjectType;
constructor(config: GraphQLInterfaceTypeConfig);
getFields(): GraphQLFieldDefinitionMap;
getPossibleTypes(): Array<GraphQLObjectType>;
isPossibleType(type: GraphQLObjectType): boolean;
getObjectType(value: any, info: GraphQLResolveInfo): GraphQLObjectType;
toString(): string;
}
interface GraphQLInterfaceTypeConfig {
name: string;
fields: GraphQLFieldConfigMapThunk | GraphQLFieldConfigMap;
resolveType?: (value: any, info?: GraphQLResolveInfo) => GraphQLObjectType;
description?: string;
}
export class GraphQLUnionType {
name: string;
description: string;
resolveType: (value: any, info?: GraphQLResolveInfo) => GraphQLObjectType;
constructor(config: GraphQLUnionTypeConfig);
getPossibleTypes(): Array<GraphQLObjectType>;
isPossibleType(type: GraphQLObjectType): boolean;
getObjectType(value: any, info: GraphQLResolveInfo): GraphQLObjectType;
toString(): string;
}
interface GraphQLUnionTypeConfig {
name: string,
types: Array<GraphQLObjectType>,
/**
* Optionally provide a custom type resolver function. If one is not provided,
* the default implementation will call `isTypeOf` on each implementing
* Object type.
*/
resolveType?: (value: any, info?: GraphQLResolveInfo) => GraphQLObjectType;
description?: string;
}
export class GraphQLEnumType {
name: string;
description: string;
constructor(config: GraphQLEnumTypeConfig);
getValues(): Array<GraphQLEnumValueDefinition>;
serialize(value: any): string;
parseValue(value: any): any;
parseLiteral(valueAST: Value): any;
toString(): string;
}
interface GraphQLEnumTypeConfig {
name: string;
values: GraphQLEnumValueConfigMap;
description?: string;
}
interface GraphQLEnumValueConfigMap {
[valueName: string]: GraphQLEnumValueConfig;
}
interface GraphQLEnumValueConfig {
value?: any;
deprecationReason?: string;
description?: string;
}
interface GraphQLEnumValueDefinition {
name: string;
description: string;
deprecationReason: string;
value: any;
}
export class GraphQLInputObjectType {
name: string;
description: string;
constructor(config: InputObjectConfig);
getFields(): InputObjectFieldMap;
toString(): string;
}
interface InputObjectConfig {
name: string;
fields: InputObjectConfigFieldMapThunk | InputObjectConfigFieldMap;
description?: string;
}
type InputObjectConfigFieldMapThunk = () => InputObjectConfigFieldMap;
interface InputObjectFieldConfig {
type: GraphQLInputType;
defaultValue?: any;
description?: string;
}
interface InputObjectConfigFieldMap {
[fieldName: string]: InputObjectFieldConfig;
}
interface InputObjectField {
name: string;
type: GraphQLInputType;
defaultValue?: any;
description?: string;
}
interface InputObjectFieldMap {
[fieldName: string]: InputObjectField;
}
export class GraphQLList {
ofType: GraphQLType;
constructor(type: GraphQLType);
toString(): string;
}
export class GraphQLNonNull {
ofType: GraphQLNullableType;
constructor(type: GraphQLNullableType);
toString(): string;
}
// type/directives.js
class GraphQLDirective {
name: string;
description: string;
args: Array<GraphQLArgument>;
onOperation: boolean;
onFragment: boolean;
onField: boolean;
constructor(config: GraphQLDirectiveConfig);
}
interface GraphQLDirectiveConfig {
name: string;
description?: string;
args?: Array<GraphQLArgument>;
onOperation?: boolean;
onFragment?: boolean;
onField?: boolean;
}
export var GraphQLIncludeDirective: GraphQLDirective;
export var GraphQLSkipDirective: GraphQLDirective;
// type/introspection.js
var __Schema: GraphQLObjectType;
type TypeKind = {[key: string]: string};
var SchemaMetaFieldDef: GraphQLFieldDefinition;
var TypeMetaFieldDef: GraphQLFieldDefinition;
var TypeNameMetaFieldDef: GraphQLFieldDefinition;
// type/scalars.js
export var GraphQLInt: GraphQLScalarType;
export var GraphQLFloat: GraphQLScalarType;
export var GraphQLString: GraphQLScalarType;
export var GraphQLBoolean: GraphQLScalarType;
export var GraphQLID: GraphQLScalarType;
// type/schema.js
export class GraphQLSchema {
constructor(config: GraphQLSchemaConfig);
getQueryType(): GraphQLObjectType;
getMutationType(): GraphQLObjectType;
getSubscriptionType(): GraphQLObjectType;
getTypeMap(): TypeMap;
getType(name: string): GraphQLType;
getDirectives(): Array<GraphQLDirective>;
getDirective(name: string): GraphQLDirective;
}
type TypeMap = { [typeName: string]: GraphQLType };
interface GraphQLSchemaConfig {
query: GraphQLObjectType;
mutation?: GraphQLObjectType;
subscription?: GraphQLObjectType;
directives?: Array<GraphQLDirective>;
}
}
declare module 'graphql/graphql' {
export * from '~graphql/graphql';
}
declare module 'graphql' {
export * from '~graphql/graphql';
}

133
typings/globals/body-parser/index.d.ts vendored Normal file
View file

@ -0,0 +1,133 @@
// Generated by typings
// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/7de6c3dd94feaeb21f20054b9f30d5dabc5efabd/body-parser/body-parser.d.ts
declare module "body-parser" {
import * as express from "express";
/**
* bodyParser: use individual json/urlencoded middlewares
* @deprecated
*/
function bodyParser(options?: {
/**
* if deflated bodies will be inflated. (default: true)
*/
inflate?: boolean;
/**
* maximum request body size. (default: '100kb')
*/
limit?: any;
/**
* function to verify body content, the parsing can be aborted by throwing an error.
*/
verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void;
/**
* only parse objects and arrays. (default: true)
*/
strict?: boolean;
/**
* passed to JSON.parse().
*/
receiver?: (key: string, value: any) => any;
/**
* parse extended syntax with the qs module. (default: true)
*/
extended?: boolean;
}): express.RequestHandler;
namespace bodyParser {
export function json(options?: {
/**
* if deflated bodies will be inflated. (default: true)
*/
inflate?: boolean;
/**
* maximum request body size. (default: '100kb')
*/
limit?: any;
/**
* request content-type to parse, passed directly to the type-is library. (default: 'json')
*/
type?: any;
/**
* function to verify body content, the parsing can be aborted by throwing an error.
*/
verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void;
/**
* only parse objects and arrays. (default: true)
*/
strict?: boolean;
/**
* passed to JSON.parse().
*/
receiver?: (key: string, value: any) => any;
}): express.RequestHandler;
export function raw(options?: {
/**
* if deflated bodies will be inflated. (default: true)
*/
inflate?: boolean;
/**
* maximum request body size. (default: '100kb')
*/
limit?: any;
/**
* request content-type to parse, passed directly to the type-is library. (default: 'application/octet-stream')
*/
type?: any;
/**
* function to verify body content, the parsing can be aborted by throwing an error.
*/
verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void;
}): express.RequestHandler;
export function text(options?: {
/**
* if deflated bodies will be inflated. (default: true)
*/
inflate?: boolean;
/**
* maximum request body size. (default: '100kb')
*/
limit?: any;
/**
* request content-type to parse, passed directly to the type-is library. (default: 'text/plain')
*/
type?: any;
/**
* function to verify body content, the parsing can be aborted by throwing an error.
*/
verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void;
/**
* the default charset to parse as, if not specified in content-type. (default: 'utf-8')
*/
defaultCharset?: string;
}): express.RequestHandler;
export function urlencoded(options: {
/**
* if deflated bodies will be inflated. (default: true)
*/
inflate?: boolean;
/**
* maximum request body size. (default: '100kb')
*/
limit?: any;
/**
* request content-type to parse, passed directly to the type-is library. (default: 'urlencoded')
*/
type?: any;
/**
* function to verify body content, the parsing can be aborted by throwing an error.
*/
verify?: (req: express.Request, res: express.Response, buf: Buffer, encoding: string) => void;
/**
* parse extended syntax with the qs module.
*/
extended: boolean;
}): express.RequestHandler;
}
export = bodyParser;
}

View file

@ -0,0 +1,8 @@
{
"resolution": "main",
"tree": {
"src": "https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/7de6c3dd94feaeb21f20054b9f30d5dabc5efabd/body-parser/body-parser.d.ts",
"raw": "registry:dt/body-parser#0.0.0+20160317120654",
"typings": "https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/7de6c3dd94feaeb21f20054b9f30d5dabc5efabd/body-parser/body-parser.d.ts"
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,8 @@
{
"resolution": "main",
"tree": {
"src": "https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/fb2e78984b7076eda628892770a4314d618ac0d7/express-serve-static-core/express-serve-static-core.d.ts",
"raw": "registry:dt/express-serve-static-core#0.0.0+20160322035842",
"typings": "https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/fb2e78984b7076eda628892770a4314d618ac0d7/express-serve-static-core/express-serve-static-core.d.ts"
}
}

41
typings/globals/express/index.d.ts vendored Normal file
View file

@ -0,0 +1,41 @@
// Generated by typings
// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/7de6c3dd94feaeb21f20054b9f30d5dabc5efabd/express/express.d.ts
declare module "express" {
import * as serveStatic from "serve-static";
import * as core from "express-serve-static-core";
/**
* Creates an Express application. The express() function is a top-level function exported by the express module.
*/
function e(): core.Express;
namespace e {
/**
* This is the only built-in middleware function in Express. It serves static files and is based on serve-static.
*/
var static: typeof serveStatic;
export function Router(options?: any): core.Router;
interface Application extends core.Application { }
interface CookieOptions extends core.CookieOptions { }
interface Errback extends core.Errback { }
interface ErrorRequestHandler extends core.ErrorRequestHandler { }
interface Express extends core.Express { }
interface Handler extends core.Handler { }
interface IRoute extends core.IRoute { }
interface IRouter<T> extends core.IRouter<T> { }
interface IRouterMatcher<T> extends core.IRouterMatcher<T> { }
interface MediaType extends core.MediaType { }
interface NextFunction extends core.NextFunction { }
interface Request extends core.Request { }
interface RequestHandler extends core.RequestHandler { }
interface RequestParamHandler extends core.RequestParamHandler { }
export interface Response extends core.Response { }
interface Router extends core.Router { }
interface Send extends core.Send { }
}
export = e;
}

View file

@ -0,0 +1,8 @@
{
"resolution": "main",
"tree": {
"src": "https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/7de6c3dd94feaeb21f20054b9f30d5dabc5efabd/express/express.d.ts",
"raw": "registry:dt/express#4.0.0+20160317120654",
"typings": "https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/7de6c3dd94feaeb21f20054b9f30d5dabc5efabd/express/express.d.ts"
}
}

2419
typings/globals/hapi/index.d.ts vendored Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,8 @@
{
"resolution": "main",
"tree": {
"src": "https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/ccb4c316dcafde1bda8cd3aedbd2b95cbff20b47/hapi/hapi.d.ts",
"raw": "registry:dt/hapi#13.0.0+20160521152637",
"typings": "https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/ccb4c316dcafde1bda8cd3aedbd2b95cbff20b47/hapi/hapi.d.ts"
}
}

126
typings/globals/koa/index.d.ts vendored Normal file
View file

@ -0,0 +1,126 @@
// Generated by typings
// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/7de6c3dd94feaeb21f20054b9f30d5dabc5efabd/koa/koa.d.ts
declare module "koa" {
import { EventEmitter } from "events";
import * as http from "http";
import * as net from "net";
namespace Koa {
export interface Context extends Request, Response {
body?: any;
request?: Request;
response?: Response;
originalUrl?: string;
state?: any;
name?: string;
cookies?: any;
writable?: Boolean;
respond?: Boolean;
app?: Koa;
req?: http.IncomingMessage;
res?: http.ServerResponse;
onerror(err: any): void;
toJSON(): any;
inspect(): any;
throw(code?: any, message?: any): void;
assert(): void;
}
export interface Request {
_querycache?: string;
app?: Koa;
req?: http.IncomingMessage;
res?: http.ServerResponse;
response?: Response;
ctx?: Context;
headers?: any;
header?: any;
method?: string;
length?: any;
url?: string;
origin?: string;
originalUrl?: string;
href?: string;
path?: string;
querystring?: string;
query?: any;
search?: string;
idempotent?: Boolean;
socket?: net.Socket;
protocol?: string;
host?: string;
hostname?: string;
fresh?: Boolean;
stale?: Boolean;
charset?: string;
secure?: Boolean;
ips?: Array<string>;
ip?: string;
subdomains?: Array<string>;
accept?: any;
type?: string;
accepts?: () => any;
acceptsEncodings?: () => any;
acceptsCharsets?: () => any;
acceptsLanguages?: () => any;
is?: (types: any) => any;
toJSON?: () => any;
inspect?: () => any;
get?: (field: string) => string;
}
export interface Response {
_body?: any;
_explicitStatus?: Boolean;
app?: Koa;
res?: http.ServerResponse;
req?: http.IncomingMessage;
ctx?: Context;
request?: Request;
socket?: net.Socket;
header?: any;
headers?: any;
status?: number;
message?: string;
type?: string;
body?: any;
length?: any;
headerSent?: Boolean;
lastModified?: Date;
etag?: string;
writable?: Boolean;
is?: (types: any) => any;
redirect?: (url: string, alt: string) => void;
attachment?: (filename?: string) => void;
vary?: (field: string) => void;
get?: (field: string) => string;
set?: (field: any, val: any) => void;
remove?: (field: string) => void;
append?: (field: string, val: any) => void;
toJSON?: () => any;
inspect?: () => any;
}
}
class Koa extends EventEmitter {
keys: Array<string>;
subdomainOffset: number;
proxy: Boolean;
server: http.Server;
env: string;
context: Koa.Context;
request: Koa.Request;
response: Koa.Response;
silent: Boolean;
constructor();
use(middleware: (ctx: Koa.Context, next: Function) => any): Koa;
callback(): (req: http.IncomingMessage, res: http.ServerResponse) => void;
listen(port: number, callback?: Function): http.Server;
toJSON(): any;
inspect(): any;
onerror(err: any): void;
}
namespace Koa {}
export = Koa;
}

View file

@ -0,0 +1,8 @@
{
"resolution": "main",
"tree": {
"src": "https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/7de6c3dd94feaeb21f20054b9f30d5dabc5efabd/koa/koa.d.ts",
"raw": "registry:dt/koa#2.0.0+20160317120654",
"typings": "https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/7de6c3dd94feaeb21f20054b9f30d5dabc5efabd/koa/koa.d.ts"
}
}

15
typings/globals/mime/index.d.ts vendored Normal file
View file

@ -0,0 +1,15 @@
// Generated by typings
// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/56295f5058cac7ae458540423c50ac2dcf9fc711/mime/mime.d.ts
declare module "mime" {
export function lookup(path: string): string;
export function extension(mime: string): string;
export function load(filepath: string): void;
export function define(mimes: Object): void;
interface Charsets {
lookup(mime: string): string;
}
export var charsets: Charsets;
export var default_type: string;
}

View file

@ -0,0 +1,8 @@
{
"resolution": "main",
"tree": {
"src": "https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/56295f5058cac7ae458540423c50ac2dcf9fc711/mime/mime.d.ts",
"raw": "registry:dt/mime#0.0.0+20160316155526",
"typings": "https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/56295f5058cac7ae458540423c50ac2dcf9fc711/mime/mime.d.ts"
}
}

233
typings/globals/mocha/index.d.ts vendored Normal file
View file

@ -0,0 +1,233 @@
// Generated by typings
// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/7de6c3dd94feaeb21f20054b9f30d5dabc5efabd/mocha/mocha.d.ts
interface MochaSetupOptions {
//milliseconds to wait before considering a test slow
slow?: number;
// timeout in milliseconds
timeout?: number;
// ui name "bdd", "tdd", "exports" etc
ui?: string;
//array of accepted globals
globals?: any[];
// reporter instance (function or string), defaults to `mocha.reporters.Spec`
reporter?: any;
// bail on the first test failure
bail?: boolean;
// ignore global leaks
ignoreLeaks?: boolean;
// grep string or regexp to filter tests with
grep?: any;
}
interface MochaDone {
(error?: Error): void;
}
declare var mocha: Mocha;
declare var describe: Mocha.IContextDefinition;
declare var xdescribe: Mocha.IContextDefinition;
// alias for `describe`
declare var context: Mocha.IContextDefinition;
// alias for `describe`
declare var suite: Mocha.IContextDefinition;
declare var it: Mocha.ITestDefinition;
declare var xit: Mocha.ITestDefinition;
// alias for `it`
declare var test: Mocha.ITestDefinition;
declare function before(action: () => void): void;
declare function before(action: (done: MochaDone) => void): void;
declare function before(description: string, action: () => void): void;
declare function before(description: string, action: (done: MochaDone) => void): void;
declare function setup(action: () => void): void;
declare function setup(action: (done: MochaDone) => void): void;
declare function after(action: () => void): void;
declare function after(action: (done: MochaDone) => void): void;
declare function after(description: string, action: () => void): void;
declare function after(description: string, action: (done: MochaDone) => void): void;
declare function teardown(action: () => void): void;
declare function teardown(action: (done: MochaDone) => void): void;
declare function beforeEach(action: () => void): void;
declare function beforeEach(action: (done: MochaDone) => void): void;
declare function beforeEach(description: string, action: () => void): void;
declare function beforeEach(description: string, action: (done: MochaDone) => void): void;
declare function suiteSetup(action: () => void): void;
declare function suiteSetup(action: (done: MochaDone) => void): void;
declare function afterEach(action: () => void): void;
declare function afterEach(action: (done: MochaDone) => void): void;
declare function afterEach(description: string, action: () => void): void;
declare function afterEach(description: string, action: (done: MochaDone) => void): void;
declare function suiteTeardown(action: () => void): void;
declare function suiteTeardown(action: (done: MochaDone) => void): void;
declare class Mocha {
constructor(options?: {
grep?: RegExp;
ui?: string;
reporter?: string;
timeout?: number;
bail?: boolean;
});
/** Setup mocha with the given options. */
setup(options: MochaSetupOptions): Mocha;
bail(value?: boolean): Mocha;
addFile(file: string): Mocha;
/** Sets reporter by name, defaults to "spec". */
reporter(name: string): Mocha;
/** Sets reporter constructor, defaults to mocha.reporters.Spec. */
reporter(reporter: (runner: Mocha.IRunner, options: any) => any): Mocha;
ui(value: string): Mocha;
grep(value: string): Mocha;
grep(value: RegExp): Mocha;
invert(): Mocha;
ignoreLeaks(value: boolean): Mocha;
checkLeaks(): Mocha;
/**
* Function to allow assertion libraries to throw errors directly into mocha.
* This is useful when running tests in a browser because window.onerror will
* only receive the 'message' attribute of the Error.
*/
throwError(error: Error): void;
/** Enables growl support. */
growl(): Mocha;
globals(value: string): Mocha;
globals(values: string[]): Mocha;
useColors(value: boolean): Mocha;
useInlineDiffs(value: boolean): Mocha;
timeout(value: number): Mocha;
slow(value: number): Mocha;
enableTimeouts(value: boolean): Mocha;
asyncOnly(value: boolean): Mocha;
noHighlighting(value: boolean): Mocha;
/** Runs tests and invokes `onComplete()` when finished. */
run(onComplete?: (failures: number) => void): Mocha.IRunner;
}
// merge the Mocha class declaration with a module
declare namespace Mocha {
/** Partial interface for Mocha's `Runnable` class. */
interface IRunnable {
title: string;
fn: Function;
async: boolean;
sync: boolean;
timedOut: boolean;
}
/** Partial interface for Mocha's `Suite` class. */
interface ISuite {
parent: ISuite;
title: string;
fullTitle(): string;
}
/** Partial interface for Mocha's `Test` class. */
interface ITest extends IRunnable {
parent: ISuite;
pending: boolean;
fullTitle(): string;
}
/** Partial interface for Mocha's `Runner` class. */
interface IRunner {}
interface IContextDefinition {
(description: string, spec: () => void): ISuite;
only(description: string, spec: () => void): ISuite;
skip(description: string, spec: () => void): void;
timeout(ms: number): void;
}
interface ITestDefinition {
(expectation: string, assertion?: () => void): ITest;
(expectation: string, assertion?: (done: MochaDone) => void): ITest;
only(expectation: string, assertion?: () => void): ITest;
only(expectation: string, assertion?: (done: MochaDone) => void): ITest;
skip(expectation: string, assertion?: () => void): void;
skip(expectation: string, assertion?: (done: MochaDone) => void): void;
timeout(ms: number): void;
}
export module reporters {
export class Base {
stats: {
suites: number;
tests: number;
passes: number;
pending: number;
failures: number;
};
constructor(runner: IRunner);
}
export class Doc extends Base {}
export class Dot extends Base {}
export class HTML extends Base {}
export class HTMLCov extends Base {}
export class JSON extends Base {}
export class JSONCov extends Base {}
export class JSONStream extends Base {}
export class Landing extends Base {}
export class List extends Base {}
export class Markdown extends Base {}
export class Min extends Base {}
export class Nyan extends Base {}
export class Progress extends Base {
/**
* @param options.open String used to indicate the start of the progress bar.
* @param options.complete String used to indicate a complete test on the progress bar.
* @param options.incomplete String used to indicate an incomplete test on the progress bar.
* @param options.close String used to indicate the end of the progress bar.
*/
constructor(runner: IRunner, options?: {
open?: string;
complete?: string;
incomplete?: string;
close?: string;
});
}
export class Spec extends Base {}
export class TAP extends Base {}
export class XUnit extends Base {
constructor(runner: IRunner, options?: any);
}
}
}
declare module "mocha" {
export = Mocha;
}

View file

@ -0,0 +1,8 @@
{
"resolution": "main",
"tree": {
"src": "https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/7de6c3dd94feaeb21f20054b9f30d5dabc5efabd/mocha/mocha.d.ts",
"raw": "registry:dt/mocha#2.2.5+20160317120654",
"typings": "https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/7de6c3dd94feaeb21f20054b9f30d5dabc5efabd/mocha/mocha.d.ts"
}
}

2382
typings/globals/node/index.d.ts vendored Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,8 @@
{
"resolution": "main",
"tree": {
"src": "https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/9081e075b730c9948b643a6c38d6deb18cb0ebdd/node/node.d.ts",
"raw": "registry:dt/node#6.0.0+20160524002506",
"typings": "https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/9081e075b730c9948b643a6c38d6deb18cb0ebdd/node/node.d.ts"
}
}

79
typings/globals/serve-static/index.d.ts vendored Normal file
View file

@ -0,0 +1,79 @@
// Generated by typings
// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/25fde56c8d1ba7aa5fb700e928f5413e047561f3/serve-static/serve-static.d.ts
declare module "serve-static" {
import * as express from "express-serve-static-core";
/**
* Create a new middleware function to serve files from within a given root directory.
* The file to serve will be determined by combining req.url with the provided root directory.
* When a file is not found, instead of sending a 404 response, this module will instead call next() to move on to the next middleware, allowing for stacking and fall-backs.
*/
function serveStatic(root: string, options?: {
/**
* Set how "dotfiles" are treated when encountered. A dotfile is a file or directory that begins with a dot (".").
* Note this check is done on the path itself without checking if the path actually exists on the disk.
* If root is specified, only the dotfiles above the root are checked (i.e. the root itself can be within a dotfile when when set to "deny").
* The default value is 'ignore'.
* 'allow' No special treatment for dotfiles
* 'deny' Send a 403 for any request for a dotfile
* 'ignore' Pretend like the dotfile does not exist and call next()
*/
dotfiles?: string;
/**
* Enable or disable etag generation, defaults to true.
*/
etag?: boolean;
/**
* Set file extension fallbacks. When set, if a file is not found, the given extensions will be added to the file name and search for.
* The first that exists will be served. Example: ['html', 'htm'].
* The default value is false.
*/
extensions?: string[];
/**
* Let client errors fall-through as unhandled requests, otherwise forward a client error.
* The default value is false.
*/
fallthrough?: boolean;
/**
* By default this module will send "index.html" files in response to a request on a directory.
* To disable this set false or to supply a new index pass a string or an array in preferred order.
*/
index?: boolean|string|string[];
/**
* Enable or disable Last-Modified header, defaults to true. Uses the file system's last modified value.
*/
lastModified?: boolean;
/**
* Provide a max-age in milliseconds for http caching, defaults to 0. This can also be a string accepted by the ms module.
*/
maxAge?: number|string;
/**
* Redirect to trailing "/" when the pathname is a dir. Defaults to true.
*/
redirect?: boolean;
/**
* Function to set custom headers on response. Alterations to the headers need to occur synchronously.
* The function is called as fn(res, path, stat), where the arguments are:
* res the response object
* path the file path that is being sent
* stat the stat object of the file that is being sent
*/
setHeaders?: (res: express.Response, path: string, stat: any) => any;
}): express.Handler;
import * as m from "mime";
namespace serveStatic {
var mime: typeof m;
}
export = serveStatic;
}

View file

@ -0,0 +1,8 @@
{
"resolution": "main",
"tree": {
"src": "https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/25fde56c8d1ba7aa5fb700e928f5413e047561f3/serve-static/serve-static.d.ts",
"raw": "registry:dt/serve-static#0.0.0+20160501131543",
"typings": "https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/25fde56c8d1ba7aa5fb700e928f5413e047561f3/serve-static/serve-static.d.ts"
}
}

10
typings/index.d.ts vendored Normal file
View file

@ -0,0 +1,10 @@
/// <reference path="globals/body-parser/index.d.ts" />
/// <reference path="globals/express-serve-static-core/index.d.ts" />
/// <reference path="globals/express/index.d.ts" />
/// <reference path="globals/hapi/index.d.ts" />
/// <reference path="globals/koa/index.d.ts" />
/// <reference path="globals/mime/index.d.ts" />
/// <reference path="globals/mocha/index.d.ts" />
/// <reference path="globals/node/index.d.ts" />
/// <reference path="globals/serve-static/index.d.ts" />
/// <reference path="modules/graphql/index.d.ts" />

1
typings/main.d.ts vendored Normal file
View file

@ -0,0 +1 @@
/// <reference path="main/definitions/graphql/index.d.ts" />

View file

@ -0,0 +1,955 @@
// Generated by typings
// Source: https://raw.githubusercontent.com/nitintutlani/typed-graphql/master/graphql.d.ts
declare module '~graphql/graphql' {
// graphql.js
export function graphql(
schema: GraphQLSchema,
requestString: string,
rootValue?: any,
contextValue?: any,
variableValues?: { [key: string]: any },
operationName?: string
): Promise<GraphQLResult>;
interface GraphQLResult {
data?: any;
errors?: Array<GraphQLError>;
}
// error/*.js
class GraphQLError extends Error {
constructor(
message: string,
nodes?: Array<any>,
stack?: string,
source?: Source,
positions?: Array<number>
);
}
export function formatError(error: GraphQLError): GraphQLFormattedError;
interface GraphQLFormattedError {
message: string,
locations: Array<GraphQLErrorLocation>
}
interface GraphQLErrorLocation {
line: number,
column: number
}
function locatedError(originalError: Error, nodes: Array<any>): GraphQLError;
function syntaxError(source: Source, position: number, description: string): GraphQLError;
// execution/*.js
interface ExecutionContext {
schema: GraphQLSchema;
fragments: {[key: string]: FragmentDefinition};
rootValue: any;
operation: OperationDefinition;
variableValues: {[key: string]: any};
errors: Array<GraphQLError>;
}
interface ExecutionResult {
data: any;
errors?: Array<GraphQLError>;
}
function execute(
schema: GraphQLSchema,
documentAST: Document,
rootValue?: any,
contextValue?: any,
variableValues?: {[key: string]: any},
operationName?: string
): Promise<ExecutionResult>;
function getVariableValues(
schema: GraphQLSchema,
definitionASTs: Array<VariableDefinition>,
inputs: { [key: string]: any }
): { [key: string]: any };
function getArgumentValues(
argDefs: Array<GraphQLArgument>,
argASTs: Array<Argument>,
variableValues: { [key: string]: any }
): { [key: string]: any };
// validation/*.js
function validate(
schema: GraphQLSchema,
ast: Document,
rules?: Array<any>
): Array<GraphQLError>;
// jsutils/*.js
function find<T>(list: Array<T>, predicate: (item: T) => boolean): T;
function invariant(condition: any, message: string): void;
function isNullish(value: any): boolean;
function keyMap<T>(
list: Array<T>,
keyFn: (item: T) => string
): {[key: string]: T};
function keyValMap<T, V>(
list: Array<T>,
keyFn: (item: T) => string,
valFn: (item: T) => V
): {[key: string]: V}
// language/ast.js
interface Location {
start: number;
end: number;
source?: Source
}
type Node = Name
| Document
| OperationDefinition
| VariableDefinition
| Variable
| SelectionSet
| Field
| Argument
| FragmentSpread
| InlineFragment
| FragmentDefinition
| IntValue
| FloatValue
| StringValue
| BooleanValue
| EnumValue
| ListValue
| ObjectValue
| ObjectField
| Directive
| ListType
| NonNullType
| ObjectTypeDefinition
| FieldDefinition
| InputValueDefinition
| InterfaceTypeDefinition
| UnionTypeDefinition
| ScalarTypeDefinition
| EnumTypeDefinition
| EnumValueDefinition
| InputObjectTypeDefinition
| TypeExtensionDefinition;
interface Name {
kind: string;
loc?: Location;
value: string;
}
interface Document {
kind: string;
loc?: Location;
definitions: Array<Definition>;
}
type Definition = OperationDefinition
| FragmentDefinition
| TypeDefinition;
interface OperationDefinition {
kind: string;
loc?: Location;
// Note: subscription is an experimental non-spec addition.
operation: string;
name?: Name;
variableDefinitions?: Array<VariableDefinition>;
directives?: Array<Directive>;
selectionSet: SelectionSet;
}
interface VariableDefinition {
kind: string;
loc?: Location;
variable: Variable;
type: Type;
defaultValue?: Value;
}
interface Variable {
kind: string;
loc?: Location;
name: Name;
}
interface SelectionSet {
kind: string;
loc?: Location;
selections: Array<Selection>;
}
type Selection = Field
| FragmentSpread
| InlineFragment;
interface Field {
kind: string;
loc?: Location;
alias?: Name;
name: Name;
arguments?: Array<Argument>;
directives?: Array<Directive>;
selectionSet?: SelectionSet;
}
interface Argument {
kind: string;
loc?: Location;
name: Name;
value: Value;
}
// Fragments
interface FragmentSpread {
kind: string;
loc?: Location;
name: Name;
directives?: Array<Directive>;
}
interface InlineFragment {
kind: string;
loc?: Location;
typeCondition?: NamedType;
directives?: Array<Directive>;
selectionSet: SelectionSet;
}
interface FragmentDefinition {
kind: string;
loc?: Location;
name: Name;
typeCondition: NamedType;
directives?: Array<Directive>;
selectionSet: SelectionSet;
}
// Values
type Value = Variable
| IntValue
| FloatValue
| StringValue
| BooleanValue
| EnumValue
| ListValue
| ObjectValue;
interface IntValue {
kind: string;
loc?: Location;
value: string;
}
interface FloatValue {
kind: string;
loc?: Location;
value: string;
}
interface StringValue {
kind: string;
loc?: Location;
value: string;
}
interface BooleanValue {
kind: string;
loc?: Location;
value: boolean;
}
interface EnumValue {
kind: string;
loc?: Location;
value: string;
}
interface ListValue {
kind: string;
loc?: Location;
values: Array<Value>;
}
interface ObjectValue {
kind: string;
loc?: Location;
fields: Array<ObjectField>;
}
interface ObjectField {
kind: string;
loc?: Location;
name: Name;
value: Value;
}
// Directives
interface Directive {
kind: string;
loc?: Location;
name: Name;
arguments?: Array<Argument>;
}
// Type Reference
type Type = NamedType
| ListType
| NonNullType;
interface NamedType {
kind: string;
loc?: Location;
name: Name;
}
interface ListType {
kind: string;
loc?: Location;
type: Type;
}
interface NonNullType {
kind: string;
loc?: Location;
type: NamedType | ListType;
}
// Type Definition
type TypeDefinition = ObjectTypeDefinition
| InterfaceTypeDefinition
| UnionTypeDefinition
| ScalarTypeDefinition
| EnumTypeDefinition
| InputObjectTypeDefinition
| TypeExtensionDefinition;
interface ObjectTypeDefinition {
kind: string;
loc?: Location;
name: Name;
interfaces?: Array<NamedType>;
fields: Array<FieldDefinition>;
}
interface FieldDefinition {
kind: string;
loc?: Location;
name: Name;
arguments: Array<InputValueDefinition>;
type: Type;
}
interface InputValueDefinition {
kind: string;
loc?: Location;
name: Name;
type: Type;
defaultValue?: Value;
}
interface InterfaceTypeDefinition {
kind: string;
loc?: Location;
name: Name;
fields: Array<FieldDefinition>;
}
interface UnionTypeDefinition {
kind: string;
loc?: Location;
name: Name;
types: Array<NamedType>;
}
interface ScalarTypeDefinition {
kind: string;
loc?: Location;
name: Name;
}
interface EnumTypeDefinition {
kind: string;
loc?: Location;
name: Name;
values: Array<EnumValueDefinition>;
}
interface EnumValueDefinition {
kind: string;
loc?: Location;
name: Name;
}
interface InputObjectTypeDefinition {
kind: string;
loc?: Location;
name: Name;
fields: Array<InputValueDefinition>;
}
interface TypeExtensionDefinition {
kind: string;
loc?: Location;
definition: ObjectTypeDefinition;
}
// language/kinds.js
const NAME: string;
// Document
const DOCUMENT: string;
const OPERATION_DEFINITION: string;
const VARIABLE_DEFINITION: string;
const VARIABLE: string;
const SELECTION_SET: string;
const FIELD: string;
const ARGUMENT: string;
// Fragments
const FRAGMENT_SPREAD: string;
const INLINE_FRAGMENT: string;
const FRAGMENT_DEFINITION: string;
// Values
const INT: string;
const FLOAT: string;
const STRING: string;
const BOOLEAN: string;
const ENUM: string;
const LIST: string;
const OBJECT: string;
const OBJECT_FIELD: string;
// Directives
const DIRECTIVE: string;
// Types
const NAMED_TYPE: string;
const LIST_TYPE: string;
const NON_NULL_TYPE: string;
// Type Definitions
const OBJECT_TYPE_DEFINITION: string;
const FIELD_DEFINITION: string;
const INPUT_VALUE_DEFINITION: string;
const INTERFACE_TYPE_DEFINITION: string;
const UNION_TYPE_DEFINITION: string;
const SCALAR_TYPE_DEFINITION: string;
const ENUM_TYPE_DEFINITION: string;
const ENUM_VALUE_DEFINITION: string;
const INPUT_OBJECT_TYPE_DEFINITION: string;
const TYPE_EXTENSION_DEFINITION: string;
// language/lexer.js
interface Token {
kind: number;
start: number;
end: number;
value: string;
}
type Lexer = (resetPosition?: number) => Token;
function lex(source: Source): Lexer;
type TokenKind = {[key: string]: number};
function getTokenDesc(token: Token): string;
function getTokenKindDesc(kind: number): string;
// language/location.js
interface SourceLocation {
line: number;
column: number;
}
function getLocation(source: Source, position: number): SourceLocation;
// language/parser.js
interface ParseOptions {
noLocation?: boolean,
noSource?: boolean,
}
function parse(
source: Source | string,
options?: ParseOptions
): Document;
function parseValue(
source: Source | string,
options?: ParseOptions
): Value;
function parseConstValue(parser: any): Value;
function parseType(parser: any): Type;
function parseNamedType(parser: any): NamedType;
// language/printer.js
function print(ast: any): string;
// language/source.js
class Source {
body: string;
name: string;
constructor(body: string, name?: string);
}
// language/visitor.js
interface QueryDocumentKeys {
Name: any[];
Document: string[];
OperationDefinition: string[];
VariableDefinition: string[];
Variable: string[];
SelectionSet: string[];
Field: string[];
Argument: string[];
FragmentSpread: string[];
InlineFragment: string[];
FragmentDefinition: string[];
IntValue: number[];
FloatValue: number[];
StringValue: string[];
BooleanValue: boolean[];
EnumValue: any[];
ListValue: string[];
ObjectValue: string[];
ObjectField: string[];
Directive: string[];
NamedType: string[];
ListType: string[];
NonNullType: string[];
ObjectTypeDefinition: string[];
FieldDefinition: string[];
InputValueDefinition: string[];
InterfaceTypeDefinition: string[];
UnionTypeDefinition: string[];
ScalarTypeDefinition: string[];
EnumTypeDefinition: string[];
EnumValueDefinition: string[];
InputObjectTypeDefinition: string[];
TypeExtensionDefinition: string[];
}
const BREAK: Object;
function visit(root: any, visitor: any, keyMap: any): any;
function visitInParallel(visitors: any): any;
function visitWithTypeInfo(typeInfo: any, visitor: any): any;
// type/definition.js
type GraphQLType =
GraphQLScalarType |
GraphQLObjectType |
GraphQLInterfaceType |
GraphQLUnionType |
GraphQLEnumType |
GraphQLInputObjectType |
GraphQLList |
GraphQLNonNull;
function isType(type: any): boolean;
type GraphQLInputType =
GraphQLScalarType |
GraphQLEnumType |
GraphQLInputObjectType |
GraphQLList |
GraphQLNonNull;
function isInputType(type: GraphQLType): boolean;
type GraphQLOutputType =
GraphQLScalarType |
GraphQLObjectType |
GraphQLInterfaceType |
GraphQLUnionType |
GraphQLEnumType |
GraphQLList |
GraphQLNonNull;
function isOutputType(type: GraphQLType): boolean;
type GraphQLLeafType =
GraphQLScalarType |
GraphQLEnumType;
function isLeafType(type: GraphQLType): boolean;
type GraphQLCompositeType =
GraphQLObjectType |
GraphQLInterfaceType |
GraphQLUnionType;
function isCompositeType(type: GraphQLType): boolean;
type GraphQLAbstractType =
GraphQLInterfaceType |
GraphQLUnionType;
function isAbstractType(type: GraphQLType): boolean;
type GraphQLNullableType =
GraphQLScalarType |
GraphQLObjectType |
GraphQLInterfaceType |
GraphQLUnionType |
GraphQLEnumType |
GraphQLInputObjectType |
GraphQLList;
function getNullableType(type: GraphQLType): GraphQLNullableType;
type GraphQLNamedType =
GraphQLScalarType |
GraphQLObjectType |
GraphQLInterfaceType |
GraphQLUnionType |
GraphQLEnumType |
GraphQLInputObjectType;
function getNamedType(type: GraphQLType): GraphQLNamedType;
export class GraphQLScalarType {
constructor(config: GraphQLScalarTypeConfig);
serialize(value: any): any;
parseValue(value: any): any;
parseLiteral(valueAST: Value): any;
toString(): string;
}
interface GraphQLScalarTypeConfig {
name: string;
description?: string;
serialize: (value: any) => any;
parseValue?: (value: any) => any;
parseLiteral?: (valueAST: Value) => any;
}
export class GraphQLObjectType {
constructor(config: GraphQLObjectTypeConfig);
getFields(): GraphQLFieldDefinitionMap;
getInterfaces(): Array<GraphQLInterfaceType>;
toString(): string;
}
interface GraphQLObjectTypeConfig {
name: string;
interfaces?: GraphQLInterfacesThunk | Array<GraphQLInterfaceType>;
fields: GraphQLFieldConfigMapThunk | GraphQLFieldConfigMap;
isTypeOf?: (value: any, info?: GraphQLResolveInfo) => boolean;
description?: string
}
type GraphQLInterfacesThunk = () => Array<GraphQLInterfaceType>;
type GraphQLFieldConfigMapThunk = () => GraphQLFieldConfigMap;
type GraphQLFieldResolveFn = (
source?: any,
args?: { [argName: string]: any },
context?: any,
info?: GraphQLResolveInfo
) => any;
interface GraphQLResolveInfo {
fieldName: string,
fieldASTs: Array<Field>,
returnType: GraphQLOutputType,
parentType: GraphQLCompositeType,
schema: GraphQLSchema,
fragments: { [fragmentName: string]: FragmentDefinition },
rootValue: any,
operation: OperationDefinition,
variableValues: { [variableName: string]: any },
}
interface GraphQLFieldConfig {
type: GraphQLOutputType;
args?: GraphQLFieldConfigArgumentMap;
resolve?: GraphQLFieldResolveFn;
deprecationReason?: string;
description?: string;
}
interface GraphQLFieldConfigArgumentMap {
[argName: string]: GraphQLArgumentConfig;
}
interface GraphQLArgumentConfig {
type: GraphQLInputType;
defaultValue?: any;
description?: string;
}
interface GraphQLFieldConfigMap {
[fieldName: string]: GraphQLFieldConfig;
}
interface GraphQLFieldDefinition {
name: string;
description: string;
type: GraphQLOutputType;
args: Array<GraphQLArgument>;
resolve?: GraphQLFieldResolveFn;
deprecationReason?: string;
}
interface GraphQLArgument {
name: string;
type: GraphQLInputType;
defaultValue?: any;
description?: string;
}
interface GraphQLFieldDefinitionMap {
[fieldName: string]: GraphQLFieldDefinition;
}
export class GraphQLInterfaceType {
name: string;
description: string;
resolveType: (value: any, info?: GraphQLResolveInfo) => GraphQLObjectType;
constructor(config: GraphQLInterfaceTypeConfig);
getFields(): GraphQLFieldDefinitionMap;
getPossibleTypes(): Array<GraphQLObjectType>;
isPossibleType(type: GraphQLObjectType): boolean;
getObjectType(value: any, info: GraphQLResolveInfo): GraphQLObjectType;
toString(): string;
}
interface GraphQLInterfaceTypeConfig {
name: string;
fields: GraphQLFieldConfigMapThunk | GraphQLFieldConfigMap;
resolveType?: (value: any, info?: GraphQLResolveInfo) => GraphQLObjectType;
description?: string;
}
export class GraphQLUnionType {
name: string;
description: string;
resolveType: (value: any, info?: GraphQLResolveInfo) => GraphQLObjectType;
constructor(config: GraphQLUnionTypeConfig);
getPossibleTypes(): Array<GraphQLObjectType>;
isPossibleType(type: GraphQLObjectType): boolean;
getObjectType(value: any, info: GraphQLResolveInfo): GraphQLObjectType;
toString(): string;
}
interface GraphQLUnionTypeConfig {
name: string,
types: Array<GraphQLObjectType>,
/**
* Optionally provide a custom type resolver function. If one is not provided,
* the default implementation will call `isTypeOf` on each implementing
* Object type.
*/
resolveType?: (value: any, info?: GraphQLResolveInfo) => GraphQLObjectType;
description?: string;
}
export class GraphQLEnumType {
name: string;
description: string;
constructor(config: GraphQLEnumTypeConfig);
getValues(): Array<GraphQLEnumValueDefinition>;
serialize(value: any): string;
parseValue(value: any): any;
parseLiteral(valueAST: Value): any;
toString(): string;
}
interface GraphQLEnumTypeConfig {
name: string;
values: GraphQLEnumValueConfigMap;
description?: string;
}
interface GraphQLEnumValueConfigMap {
[valueName: string]: GraphQLEnumValueConfig;
}
interface GraphQLEnumValueConfig {
value?: any;
deprecationReason?: string;
description?: string;
}
interface GraphQLEnumValueDefinition {
name: string;
description: string;
deprecationReason: string;
value: any;
}
export class GraphQLInputObjectType {
name: string;
description: string;
constructor(config: InputObjectConfig);
getFields(): InputObjectFieldMap;
toString(): string;
}
interface InputObjectConfig {
name: string;
fields: InputObjectConfigFieldMapThunk | InputObjectConfigFieldMap;
description?: string;
}
type InputObjectConfigFieldMapThunk = () => InputObjectConfigFieldMap;
interface InputObjectFieldConfig {
type: GraphQLInputType;
defaultValue?: any;
description?: string;
}
interface InputObjectConfigFieldMap {
[fieldName: string]: InputObjectFieldConfig;
}
interface InputObjectField {
name: string;
type: GraphQLInputType;
defaultValue?: any;
description?: string;
}
interface InputObjectFieldMap {
[fieldName: string]: InputObjectField;
}
export class GraphQLList {
ofType: GraphQLType;
constructor(type: GraphQLType);
toString(): string;
}
export class GraphQLNonNull {
ofType: GraphQLNullableType;
constructor(type: GraphQLNullableType);
toString(): string;
}
// type/directives.js
class GraphQLDirective {
name: string;
description: string;
args: Array<GraphQLArgument>;
onOperation: boolean;
onFragment: boolean;
onField: boolean;
constructor(config: GraphQLDirectiveConfig);
}
interface GraphQLDirectiveConfig {
name: string;
description?: string;
args?: Array<GraphQLArgument>;
onOperation?: boolean;
onFragment?: boolean;
onField?: boolean;
}
export var GraphQLIncludeDirective: GraphQLDirective;
export var GraphQLSkipDirective: GraphQLDirective;
// type/introspection.js
var __Schema: GraphQLObjectType;
type TypeKind = {[key: string]: string};
var SchemaMetaFieldDef: GraphQLFieldDefinition;
var TypeMetaFieldDef: GraphQLFieldDefinition;
var TypeNameMetaFieldDef: GraphQLFieldDefinition;
// type/scalars.js
export var GraphQLInt: GraphQLScalarType;
export var GraphQLFloat: GraphQLScalarType;
export var GraphQLString: GraphQLScalarType;
export var GraphQLBoolean: GraphQLScalarType;
export var GraphQLID: GraphQLScalarType;
// type/schema.js
export class GraphQLSchema {
constructor(config: GraphQLSchemaConfig);
getQueryType(): GraphQLObjectType;
getMutationType(): GraphQLObjectType;
getSubscriptionType(): GraphQLObjectType;
getTypeMap(): TypeMap;
getType(name: string): GraphQLType;
getDirectives(): Array<GraphQLDirective>;
getDirective(name: string): GraphQLDirective;
}
type TypeMap = { [typeName: string]: GraphQLType };
interface GraphQLSchemaConfig {
query: GraphQLObjectType;
mutation?: GraphQLObjectType;
subscription?: GraphQLObjectType;
directives?: Array<GraphQLDirective>;
}
}
declare module 'graphql/graphql' {
export * from '~graphql/graphql';
}
declare module 'graphql' {
export * from '~graphql/graphql';
}

957
typings/modules/graphql/index.d.ts vendored Normal file
View file

@ -0,0 +1,957 @@
// Generated by typings
// Source: https://raw.githubusercontent.com/nitintutlani/typed-graphql/master/graphql.d.ts
declare module '~graphql/graphql' {
// graphql.js
export function graphql(
schema: GraphQLSchema,
requestString: string,
rootValue?: any,
contextValue?: any,
variableValues?: { [key: string]: any },
operationName?: string
): Promise<GraphQLResult>;
interface GraphQLResult {
data?: any;
errors?: Array<GraphQLError>;
}
// error/*.js
class GraphQLError extends Error {
constructor(
message: string,
nodes?: Array<any>,
stack?: string,
source?: Source,
positions?: Array<number>
);
}
export function formatError(error: GraphQLError): GraphQLFormattedError;
interface GraphQLFormattedError {
message: string,
locations: Array<GraphQLErrorLocation>
}
interface GraphQLErrorLocation {
line: number,
column: number
}
function locatedError(originalError: Error, nodes: Array<any>): GraphQLError;
function syntaxError(source: Source, position: number, description: string): GraphQLError;
// execution/*.js
interface ExecutionContext {
schema: GraphQLSchema;
fragments: {[key: string]: FragmentDefinition};
rootValue: any;
operation: OperationDefinition;
variableValues: {[key: string]: any};
errors: Array<GraphQLError>;
}
interface ExecutionResult {
data: any;
errors?: Array<GraphQLError>;
}
function execute(
schema: GraphQLSchema,
documentAST: Document,
rootValue?: any,
contextValue?: any,
variableValues?: {[key: string]: any},
operationName?: string
): Promise<ExecutionResult>;
function getVariableValues(
schema: GraphQLSchema,
definitionASTs: Array<VariableDefinition>,
inputs: { [key: string]: any }
): { [key: string]: any };
function getArgumentValues(
argDefs: Array<GraphQLArgument>,
argASTs: Array<Argument>,
variableValues: { [key: string]: any }
): { [key: string]: any };
// validation/*.js
function validate(
schema: GraphQLSchema,
ast: Document,
rules?: Array<any>
): Array<GraphQLError>;
// jsutils/*.js
function find<T>(list: Array<T>, predicate: (item: T) => boolean): T;
function invariant(condition: any, message: string): void;
function isNullish(value: any): boolean;
function keyMap<T>(
list: Array<T>,
keyFn: (item: T) => string
): {[key: string]: T};
function keyValMap<T, V>(
list: Array<T>,
keyFn: (item: T) => string,
valFn: (item: T) => V
): {[key: string]: V}
// language/ast.js
interface Location {
start: number;
end: number;
source?: Source
}
type Node = Name
| Document
| OperationDefinition
| VariableDefinition
| Variable
| SelectionSet
| Field
| Argument
| FragmentSpread
| InlineFragment
| FragmentDefinition
| IntValue
| FloatValue
| StringValue
| BooleanValue
| EnumValue
| ListValue
| ObjectValue
| ObjectField
| Directive
| ListType
| NonNullType
| ObjectTypeDefinition
| FieldDefinition
| InputValueDefinition
| InterfaceTypeDefinition
| UnionTypeDefinition
| ScalarTypeDefinition
| EnumTypeDefinition
| EnumValueDefinition
| InputObjectTypeDefinition
| TypeExtensionDefinition;
interface Name {
kind: string;
loc?: Location;
value: string;
}
interface Document {
kind: string;
loc?: Location;
definitions: Array<Definition>;
}
type Definition = OperationDefinition
| FragmentDefinition
| TypeDefinition;
interface OperationDefinition {
kind: string;
loc?: Location;
// Note: subscription is an experimental non-spec addition.
operation: string;
name?: Name;
variableDefinitions?: Array<VariableDefinition>;
directives?: Array<Directive>;
selectionSet: SelectionSet;
}
interface VariableDefinition {
kind: string;
loc?: Location;
variable: Variable;
type: Type;
defaultValue?: Value;
}
interface Variable {
kind: string;
loc?: Location;
name: Name;
}
interface SelectionSet {
kind: string;
loc?: Location;
selections: Array<Selection>;
}
type Selection = Field
| FragmentSpread
| InlineFragment;
interface Field {
kind: string;
loc?: Location;
alias?: Name;
name: Name;
arguments?: Array<Argument>;
directives?: Array<Directive>;
selectionSet?: SelectionSet;
}
interface Argument {
kind: string;
loc?: Location;
name: Name;
value: Value;
}
// Fragments
interface FragmentSpread {
kind: string;
loc?: Location;
name: Name;
directives?: Array<Directive>;
}
interface InlineFragment {
kind: string;
loc?: Location;
typeCondition?: NamedType;
directives?: Array<Directive>;
selectionSet: SelectionSet;
}
interface FragmentDefinition {
kind: string;
loc?: Location;
name: Name;
typeCondition: NamedType;
directives?: Array<Directive>;
selectionSet: SelectionSet;
}
// Values
type Value = Variable
| IntValue
| FloatValue
| StringValue
| BooleanValue
| EnumValue
| ListValue
| ObjectValue;
interface IntValue {
kind: string;
loc?: Location;
value: string;
}
interface FloatValue {
kind: string;
loc?: Location;
value: string;
}
interface StringValue {
kind: string;
loc?: Location;
value: string;
}
interface BooleanValue {
kind: string;
loc?: Location;
value: boolean;
}
interface EnumValue {
kind: string;
loc?: Location;
value: string;
}
interface ListValue {
kind: string;
loc?: Location;
values: Array<Value>;
}
interface ObjectValue {
kind: string;
loc?: Location;
fields: Array<ObjectField>;
}
interface ObjectField {
kind: string;
loc?: Location;
name: Name;
value: Value;
}
// Directives
interface Directive {
kind: string;
loc?: Location;
name: Name;
arguments?: Array<Argument>;
}
// Type Reference
type Type = NamedType
| ListType
| NonNullType;
interface NamedType {
kind: string;
loc?: Location;
name: Name;
}
interface ListType {
kind: string;
loc?: Location;
type: Type;
}
interface NonNullType {
kind: string;
loc?: Location;
type: NamedType | ListType;
}
// Type Definition
type TypeDefinition = ObjectTypeDefinition
| InterfaceTypeDefinition
| UnionTypeDefinition
| ScalarTypeDefinition
| EnumTypeDefinition
| InputObjectTypeDefinition
| TypeExtensionDefinition;
interface ObjectTypeDefinition {
kind: string;
loc?: Location;
name: Name;
interfaces?: Array<NamedType>;
fields: Array<FieldDefinition>;
}
interface FieldDefinition {
kind: string;
loc?: Location;
name: Name;
arguments: Array<InputValueDefinition>;
type: Type;
}
interface InputValueDefinition {
kind: string;
loc?: Location;
name: Name;
type: Type;
defaultValue?: Value;
}
interface InterfaceTypeDefinition {
kind: string;
loc?: Location;
name: Name;
fields: Array<FieldDefinition>;
}
interface UnionTypeDefinition {
kind: string;
loc?: Location;
name: Name;
types: Array<NamedType>;
}
interface ScalarTypeDefinition {
kind: string;
loc?: Location;
name: Name;
}
interface EnumTypeDefinition {
kind: string;
loc?: Location;
name: Name;
values: Array<EnumValueDefinition>;
}
interface EnumValueDefinition {
kind: string;
loc?: Location;
name: Name;
}
interface InputObjectTypeDefinition {
kind: string;
loc?: Location;
name: Name;
fields: Array<InputValueDefinition>;
}
interface TypeExtensionDefinition {
kind: string;
loc?: Location;
definition: ObjectTypeDefinition;
}
// language/kinds.js
const NAME: string;
// Document
const DOCUMENT: string;
const OPERATION_DEFINITION: string;
const VARIABLE_DEFINITION: string;
const VARIABLE: string;
const SELECTION_SET: string;
const FIELD: string;
const ARGUMENT: string;
// Fragments
const FRAGMENT_SPREAD: string;
const INLINE_FRAGMENT: string;
const FRAGMENT_DEFINITION: string;
// Values
const INT: string;
const FLOAT: string;
const STRING: string;
const BOOLEAN: string;
const ENUM: string;
const LIST: string;
const OBJECT: string;
const OBJECT_FIELD: string;
// Directives
const DIRECTIVE: string;
// Types
const NAMED_TYPE: string;
const LIST_TYPE: string;
const NON_NULL_TYPE: string;
// Type Definitions
const OBJECT_TYPE_DEFINITION: string;
const FIELD_DEFINITION: string;
const INPUT_VALUE_DEFINITION: string;
const INTERFACE_TYPE_DEFINITION: string;
const UNION_TYPE_DEFINITION: string;
const SCALAR_TYPE_DEFINITION: string;
const ENUM_TYPE_DEFINITION: string;
const ENUM_VALUE_DEFINITION: string;
const INPUT_OBJECT_TYPE_DEFINITION: string;
const TYPE_EXTENSION_DEFINITION: string;
// language/lexer.js
interface Token {
kind: number;
start: number;
end: number;
value: string;
}
type Lexer = (resetPosition?: number) => Token;
function lex(source: Source): Lexer;
type TokenKind = {[key: string]: number};
function getTokenDesc(token: Token): string;
function getTokenKindDesc(kind: number): string;
// language/location.js
interface SourceLocation {
line: number;
column: number;
}
function getLocation(source: Source, position: number): SourceLocation;
// language/parser.js
interface ParseOptions {
noLocation?: boolean,
noSource?: boolean,
}
function parse(
source: Source | string,
options?: ParseOptions
): Document;
function parseValue(
source: Source | string,
options?: ParseOptions
): Value;
function parseConstValue(parser: any): Value;
function parseType(parser: any): Type;
function parseNamedType(parser: any): NamedType;
// language/printer.js
function print(ast: any): string;
// language/source.js
class Source {
body: string;
name: string;
constructor(body: string, name?: string);
}
// language/visitor.js
interface QueryDocumentKeys {
Name: any[];
Document: string[];
OperationDefinition: string[];
VariableDefinition: string[];
Variable: string[];
SelectionSet: string[];
Field: string[];
Argument: string[];
FragmentSpread: string[];
InlineFragment: string[];
FragmentDefinition: string[];
IntValue: number[];
FloatValue: number[];
StringValue: string[];
BooleanValue: boolean[];
EnumValue: any[];
ListValue: string[];
ObjectValue: string[];
ObjectField: string[];
Directive: string[];
NamedType: string[];
ListType: string[];
NonNullType: string[];
ObjectTypeDefinition: string[];
FieldDefinition: string[];
InputValueDefinition: string[];
InterfaceTypeDefinition: string[];
UnionTypeDefinition: string[];
ScalarTypeDefinition: string[];
EnumTypeDefinition: string[];
EnumValueDefinition: string[];
InputObjectTypeDefinition: string[];
TypeExtensionDefinition: string[];
}
const BREAK: Object;
function visit(root: any, visitor: any, keyMap: any): any;
function visitInParallel(visitors: any): any;
function visitWithTypeInfo(typeInfo: any, visitor: any): any;
// type/definition.js
type GraphQLType =
GraphQLScalarType |
GraphQLObjectType |
GraphQLInterfaceType |
GraphQLUnionType |
GraphQLEnumType |
GraphQLInputObjectType |
GraphQLList |
GraphQLNonNull;
function isType(type: any): boolean;
type GraphQLInputType =
GraphQLScalarType |
GraphQLEnumType |
GraphQLInputObjectType |
GraphQLList |
GraphQLNonNull;
function isInputType(type: GraphQLType): boolean;
type GraphQLOutputType =
GraphQLScalarType |
GraphQLObjectType |
GraphQLInterfaceType |
GraphQLUnionType |
GraphQLEnumType |
GraphQLList |
GraphQLNonNull;
function isOutputType(type: GraphQLType): boolean;
type GraphQLLeafType =
GraphQLScalarType |
GraphQLEnumType;
function isLeafType(type: GraphQLType): boolean;
type GraphQLCompositeType =
GraphQLObjectType |
GraphQLInterfaceType |
GraphQLUnionType;
function isCompositeType(type: GraphQLType): boolean;
type GraphQLAbstractType =
GraphQLInterfaceType |
GraphQLUnionType;
function isAbstractType(type: GraphQLType): boolean;
type GraphQLNullableType =
GraphQLScalarType |
GraphQLObjectType |
GraphQLInterfaceType |
GraphQLUnionType |
GraphQLEnumType |
GraphQLInputObjectType |
GraphQLList;
function getNullableType(type: GraphQLType): GraphQLNullableType;
type GraphQLNamedType =
GraphQLScalarType |
GraphQLObjectType |
GraphQLInterfaceType |
GraphQLUnionType |
GraphQLEnumType |
GraphQLInputObjectType;
function getNamedType(type: GraphQLType): GraphQLNamedType;
export class GraphQLScalarType {
constructor(config: GraphQLScalarTypeConfig);
serialize(value: any): any;
parseValue(value: any): any;
parseLiteral(valueAST: Value): any;
toString(): string;
}
interface GraphQLScalarTypeConfig {
name: string;
description?: string;
serialize: (value: any) => any;
parseValue?: (value: any) => any;
parseLiteral?: (valueAST: Value) => any;
}
export class GraphQLObjectType {
constructor(config: GraphQLObjectTypeConfig);
getFields(): GraphQLFieldDefinitionMap;
getInterfaces(): Array<GraphQLInterfaceType>;
toString(): string;
}
interface GraphQLObjectTypeConfig {
name: string;
interfaces?: GraphQLInterfacesThunk | Array<GraphQLInterfaceType>;
fields: GraphQLFieldConfigMapThunk | GraphQLFieldConfigMap;
isTypeOf?: (value: any, info?: GraphQLResolveInfo) => boolean;
description?: string
}
type GraphQLInterfacesThunk = () => Array<GraphQLInterfaceType>;
type GraphQLFieldConfigMapThunk = () => GraphQLFieldConfigMap;
type GraphQLFieldResolveFn = (
source?: any,
args?: { [argName: string]: any },
context?: any,
info?: GraphQLResolveInfo
) => any;
interface GraphQLResolveInfo {
fieldName: string,
fieldASTs: Array<Field>,
returnType: GraphQLOutputType,
parentType: GraphQLCompositeType,
schema: GraphQLSchema,
fragments: { [fragmentName: string]: FragmentDefinition },
rootValue: any,
operation: OperationDefinition,
variableValues: { [variableName: string]: any },
}
interface GraphQLFieldConfig {
type: GraphQLOutputType;
args?: GraphQLFieldConfigArgumentMap;
resolve?: GraphQLFieldResolveFn;
deprecationReason?: string;
description?: string;
}
interface GraphQLFieldConfigArgumentMap {
[argName: string]: GraphQLArgumentConfig;
}
interface GraphQLArgumentConfig {
type: GraphQLInputType;
defaultValue?: any;
description?: string;
}
interface GraphQLFieldConfigMap {
[fieldName: string]: GraphQLFieldConfig;
}
interface GraphQLFieldDefinition {
name: string;
description: string;
type: GraphQLOutputType;
args: Array<GraphQLArgument>;
resolve?: GraphQLFieldResolveFn;
deprecationReason?: string;
}
interface GraphQLArgument {
name: string;
type: GraphQLInputType;
defaultValue?: any;
description?: string;
}
interface GraphQLFieldDefinitionMap {
[fieldName: string]: GraphQLFieldDefinition;
}
export class GraphQLInterfaceType {
name: string;
description: string;
resolveType: (value: any, info?: GraphQLResolveInfo) => GraphQLObjectType;
constructor(config: GraphQLInterfaceTypeConfig);
getFields(): GraphQLFieldDefinitionMap;
getPossibleTypes(): Array<GraphQLObjectType>;
isPossibleType(type: GraphQLObjectType): boolean;
getObjectType(value: any, info: GraphQLResolveInfo): GraphQLObjectType;
toString(): string;
}
interface GraphQLInterfaceTypeConfig {
name: string;
fields: GraphQLFieldConfigMapThunk | GraphQLFieldConfigMap;
resolveType?: (value: any, info?: GraphQLResolveInfo) => GraphQLObjectType;
description?: string;
}
export class GraphQLUnionType {
name: string;
description: string;
resolveType: (value: any, info?: GraphQLResolveInfo) => GraphQLObjectType;
constructor(config: GraphQLUnionTypeConfig);
getPossibleTypes(): Array<GraphQLObjectType>;
isPossibleType(type: GraphQLObjectType): boolean;
getObjectType(value: any, info: GraphQLResolveInfo): GraphQLObjectType;
toString(): string;
}
interface GraphQLUnionTypeConfig {
name: string,
types: Array<GraphQLObjectType>,
/**
* Optionally provide a custom type resolver function. If one is not provided,
* the default implementation will call `isTypeOf` on each implementing
* Object type.
*/
resolveType?: (value: any, info?: GraphQLResolveInfo) => GraphQLObjectType;
description?: string;
}
export class GraphQLEnumType {
name: string;
description: string;
constructor(config: GraphQLEnumTypeConfig);
getValues(): Array<GraphQLEnumValueDefinition>;
serialize(value: any): string;
parseValue(value: any): any;
parseLiteral(valueAST: Value): any;
toString(): string;
}
interface GraphQLEnumTypeConfig {
name: string;
values: GraphQLEnumValueConfigMap;
description?: string;
}
interface GraphQLEnumValueConfigMap {
[valueName: string]: GraphQLEnumValueConfig;
}
interface GraphQLEnumValueConfig {
value?: any;
deprecationReason?: string;
description?: string;
}
interface GraphQLEnumValueDefinition {
name: string;
description: string;
deprecationReason: string;
value: any;
}
export class GraphQLInputObjectType {
name: string;
description: string;
constructor(config: InputObjectConfig);
getFields(): InputObjectFieldMap;
toString(): string;
}
interface InputObjectConfig {
name: string;
fields: InputObjectConfigFieldMapThunk | InputObjectConfigFieldMap;
description?: string;
}
type InputObjectConfigFieldMapThunk = () => InputObjectConfigFieldMap;
interface InputObjectFieldConfig {
type: GraphQLInputType;
defaultValue?: any;
description?: string;
}
interface InputObjectConfigFieldMap {
[fieldName: string]: InputObjectFieldConfig;
}
interface InputObjectField {
name: string;
type: GraphQLInputType;
defaultValue?: any;
description?: string;
}
interface InputObjectFieldMap {
[fieldName: string]: InputObjectField;
}
export class GraphQLList {
ofType: GraphQLType;
constructor(type: GraphQLType);
toString(): string;
}
export class GraphQLNonNull {
ofType: GraphQLNullableType;
constructor(type: GraphQLNullableType);
toString(): string;
}
// type/directives.js
class GraphQLDirective {
name: string;
description: string;
args: Array<GraphQLArgument>;
onOperation: boolean;
onFragment: boolean;
onField: boolean;
constructor(config: GraphQLDirectiveConfig);
}
interface GraphQLDirectiveConfig {
name: string;
description?: string;
args?: Array<GraphQLArgument>;
onOperation?: boolean;
onFragment?: boolean;
onField?: boolean;
}
export var GraphQLIncludeDirective: GraphQLDirective;
export var GraphQLSkipDirective: GraphQLDirective;
// type/introspection.js
var __Schema: GraphQLObjectType;
type TypeKind = {[key: string]: string};
var SchemaMetaFieldDef: GraphQLFieldDefinition;
var TypeMetaFieldDef: GraphQLFieldDefinition;
var TypeNameMetaFieldDef: GraphQLFieldDefinition;
// type/scalars.js
export var GraphQLInt: GraphQLScalarType;
export var GraphQLFloat: GraphQLScalarType;
export var GraphQLString: GraphQLScalarType;
export var GraphQLBoolean: GraphQLScalarType;
export var GraphQLID: GraphQLScalarType;
// type/schema.js
export class GraphQLSchema {
constructor(config: GraphQLSchemaConfig);
getQueryType(): GraphQLObjectType;
getMutationType(): GraphQLObjectType;
getSubscriptionType(): GraphQLObjectType;
getTypeMap(): TypeMap;
getType(name: string): GraphQLType;
getDirectives(): Array<GraphQLDirective>;
getDirective(name: string): GraphQLDirective;
}
type TypeMap = { [typeName: string]: GraphQLType };
interface GraphQLSchemaConfig {
query: GraphQLObjectType;
mutation?: GraphQLObjectType;
subscription?: GraphQLObjectType;
directives?: Array<GraphQLDirective>;
}
}
declare module 'graphql/graphql' {
import alias = require('~graphql/graphql');
export = alias;
}
declare module 'graphql' {
import alias = require('~graphql/graphql');
export = alias;
}

View file

@ -0,0 +1,11 @@
{
"resolution": "main",
"tree": {
"src": "https://raw.githubusercontent.com/nitintutlani/typed-graphql/master/typings.json",
"raw": "github:nitintutlani/typed-graphql",
"main": "graphql.d.ts",
"global": false,
"name": "graphql",
"type": "typings"
}
}