Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DO NOT MERGE YET - Feature/restify docs tests #179

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

### VNEXT

* restify integration, docs, and tests
* Fix passHeader option in GraphiQL (Both Hapi and Koa)
* Pass `ctx` instead of `ctx.request` to options function in Koa integration ([@HriBB](https://github.com/HriBB)) in [PR #154](https://github.com/apollostack/apollo-server/pull/154)
* Manage TypeScript declaration files using npm. ([@od1k](https:/github.com/od1k) in [#162](https://github.com/apollostack/apollo-server/pull/162))
Expand Down
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,27 @@ app.use(router.allowedMethods());
app.listen(PORT);
```

### Restify
```js
import restify from 'restify';
import { apolloRestify } from 'apollo-server';

const myGraphQLSchema = // ... define or import your schema here!
const PORT = 3000;

const server = restify.createServer({
name: 'restify apollo-server',
});

server.use(restify.bodyParser());
server.post('/graphql', apolloRestify({ schema: myGraphQLSchema }));

server.listen(PORT, () => {
console.log('%s listening at %s', server.name, server.url);
});

```

## Options

Apollo Server can be configured with an options object with the the following fields:
Expand Down
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@
"@types/mime": "0.0.29",
"@types/multer": "0.0.32",
"@types/node": "^6.0.41",
"@types/restify": "^2.0.33",
"@types/serve-static": "^1.7.31",
"boom": "^4.0.0",
"http-errors": "^1.5.0",
Expand Down Expand Up @@ -81,6 +82,7 @@
"mocha": "^3.1.1",
"multer": "^1.1.0",
"remap-istanbul": "^0.7.0",
"restify": "^4.1.1",
"sinon": "^1.17.5",
"supertest": "^2.0.0",
"supertest-as-promised": "^4.0.0",
Expand Down
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,5 @@ export { apolloExpress, graphiqlExpress } from './integrations/expressApollo'
export { apolloHapi, graphiqlHapi, HapiPluginOptions, HapiOptionsFunction } from './integrations/hapiApollo'
export { apolloKoa, graphiqlKoa } from './integrations/koaApollo'
export { apolloConnect, graphiqlConnect } from './integrations/connectApollo'
export { apolloRestify, graphiqlRestify } from './integrations/restifyApollo'
export { default as ApolloOptions} from './integrations/apolloOptions'
39 changes: 39 additions & 0 deletions src/integrations/restifyApollo.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import * as restify from 'restify';
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Doing this makes sure that the interfaces are properly exports as opposed to referencing them directly, so tests a few things in one :)

import { apolloRestify, graphiqlRestify } from '../';
import testSuite, { Schema, CreateAppOptions } from './integrations.test';
import { expect } from 'chai';
import ApolloOptions from './apolloOptions';

function createApp(options: CreateAppOptions = {}) {
const server = restify.createServer({
name: 'GraphQL Demo',
});

options.apolloOptions = options.apolloOptions || { schema: Schema };
if (!options.excludeParser) {
server.use(restify.bodyParser());
}

if (options.graphiqlOptions ) {
server.get('/graphiql', graphiqlRestify( options.graphiqlOptions ));
}

server.post('/graphql', apolloRestify( options.apolloOptions ));

return server;
}

describe('restifyApollo', () => {
it('throws error if called without schema', function(){
expect(() => apolloRestify(undefined as ApolloOptions)).to.throw('Apollo Server requires options.');
});

it('throws an error if called with more than one argument', function(){
expect(() => (<any>apolloRestify)({}, 'x')).to.throw(
'Apollo Server expects exactly one argument, got 2');
});
});

describe('integration:Restify', () => {
testSuite(createApp);
});
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Any help needed to add more tests ? For now, you only ensure the server is not crashing (which is a good start!).

164 changes: 164 additions & 0 deletions src/integrations/restifyApollo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
import * as restify from 'restify';
import * as graphql from 'graphql';
import * as url from 'url';
import { runQuery } from '../core/runQuery';

import ApolloOptions from './apolloOptions';
import * as GraphiQL from '../modules/renderGraphiQL';

export interface RestifyApolloOptionsFunction {
(req?: restify.Request, res?: restify.Response): ApolloOptions | Promise<ApolloOptions>;
}

// Design principles:
// - there is just one way allowed: POST request with JSON body. Nothing else.
// - simple, fast and secure
//

export interface RestifyHandler {
(req: restify.Request, res: restify.Response, next): void;
}

export function apolloRestify(options: ApolloOptions | RestifyApolloOptionsFunction): RestifyHandler {
if (!options) {
throw new Error('Apollo Server requires options.');
}

if (arguments.length > 1) {
// TODO: test this
throw new Error(`Apollo Server expects exactly one argument, got ${arguments.length}`);
}

return async (req: restify.Request, res: restify.Response, next) => {
let optionsObject: ApolloOptions;
if (isOptionsFunction(options)) {
try {
optionsObject = await options(req, res);
} catch (e) {
res.statusCode = 500;
res.write(`Invalid options provided to ApolloServer: ${e.message}`);
res.end();
}
} else {
optionsObject = options;
}

const formatErrorFn = optionsObject.formatError || graphql.formatError;

if (req.method !== 'POST') {
res.setHeader('Allow', 'POST');
res.statusCode = 405;
res.write('Apollo Server supports only POST requests.');
res.end();
return;
}

if (!req.body) {
res.statusCode = 500;
res.write('POST body missing. Did you forget "server.use(restify.bodyParser())"?');
res.end();
return;
}

let b = req.body;
let isBatch = true;
// TODO: do something different here if the body is an array.
// Throw an error if body isn't either array or object.
if (!Array.isArray(b)) {
isBatch = false;
b = [b];
}

let responses: Array<graphql.GraphQLResult> = [];
for (let requestParams of b) {
try {
const query = requestParams.query;
const operationName = requestParams.operationName;
let variables = requestParams.variables;

if (typeof variables === 'string') {
try {
variables = JSON.parse(variables);
} catch (error) {
res.statusCode = 400;
res.write('Variables are invalid JSON.');
res.end();
return;
}
}

let params = {
schema: optionsObject.schema,
query: query,
variables: variables,
context: optionsObject.context,
rootValue: optionsObject.rootValue,
operationName: operationName,
logFunction: optionsObject.logFunction,
validationRules: optionsObject.validationRules,
formatError: formatErrorFn,
formatResponse: optionsObject.formatResponse,
debug: optionsObject.debug,
};

if (optionsObject.formatParams) {
params = optionsObject.formatParams(params);
}

responses.push(await runQuery(params));
} catch (e) {
responses.push({ errors: [formatErrorFn(e)] });
}
}

res.setHeader('Content-Type', 'application/json');
if (isBatch) {
res.write(JSON.stringify(responses));
res.end();
} else {
const gqlResponse = responses[0];
if (gqlResponse.errors && typeof gqlResponse.data === 'undefined') {
res.statusCode = 400;
}
res.write(JSON.stringify(gqlResponse));
res.end();
}

};
}

function isOptionsFunction(arg: ApolloOptions | RestifyApolloOptionsFunction): arg is RestifyApolloOptionsFunction {
return typeof arg === 'function';
}

/* This middleware returns the html for the GraphiQL interactive query UI
*
* GraphiQLData arguments
*
* - endpointURL: the relative or absolute URL for the endpoint which GraphiQL will make queries to
* - (optional) query: the GraphQL query to pre-fill in the GraphiQL UI
* - (optional) variables: a JS object of variables to pre-fill in the GraphiQL UI
* - (optional) operationName: the operationName to pre-fill in the GraphiQL UI
* - (optional) result: the result of the query to pre-fill in the GraphiQL UI
*/

export function graphiqlRestify(options: GraphiQL.GraphiQLData) {
return (req: restify.Request, res: restify.Response, next) => {
const q = req.url && url.parse(req.url, true).query || {};
const query = q.query || '';
const variables = q.variables || '{}';
const operationName = q.operationName || '';


const graphiQLString = GraphiQL.renderGraphiQL({
endpointURL: options.endpointURL,
query: query || options.query,
variables: JSON.parse(variables) || options.variables,
operationName: operationName || options.operationName,
passHeader: options.passHeader,
});
res.setHeader('Content-Type', 'text/html');
res.write(graphiQLString);
res.end();
};
}
1 change: 1 addition & 0 deletions src/test/tests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,5 @@ import '../integrations/expressApollo.test';
import '../integrations/connectApollo.test';
import '../integrations/hapiApollo.test';
import '../integrations/koaApollo.test';
import '../integrations/restifyApollo.test';
import './testApolloServerHTTP';