Skip to content

Commit

Permalink
add graphql upload to stitch schemas
Browse files Browse the repository at this point in the history
  • Loading branch information
alesso-x committed Jun 1, 2021
1 parent 5486b63 commit 887c203
Show file tree
Hide file tree
Showing 5 changed files with 98 additions and 100 deletions.
87 changes: 13 additions & 74 deletions graphql-upload/README.md
@@ -1,24 +1,17 @@
# Combining local and remote schemas
# GraphQL Upload

**Watch the [chapter video](https://www.youtube.com/watch?v=8-mZqjgIdiI)**

[![Combining Schemas video](../images/video-player.png)](https://www.youtube.com/watch?v=8-mZqjgIdiI)

This example explores basic techniques for combining local and remote schemas together into one API. This covers most topics discussed in the [combining schemas documentation](https://www.graphql-tools.com/docs/stitch-combining-schemas).
This example is based off of `combining-local-and-remote-schemas`.

**This example demonstrates:**

- Adding a locally-executable schema.
- Adding a remote schema, fetched via introspection.
- Adding a remote schema, fetched from a custom SDL service.
- Avoiding schema conflicts using transforms.
- Authorization headers.
- Basic error handling.
- Adding GraphQL Upload

## Setup

```shell
cd combining-local-and-remote-schemas
cd graphql-upload

yarn install
yarn start
Expand All @@ -28,7 +21,6 @@ The following services are available for interactive queries:

- **Stitched gateway:** http://localhost:4000/graphql
- _Products subservice_: http://localhost:4001/graphql
- _Storefronts subservice_: http://localhost:4002/graphql

## Summary

Expand All @@ -40,78 +32,25 @@ query {
upc
name
}
rainforestProduct(upc: "2") {
upc
name
}
storefront(id: "2") {
id
name
}
errorCodes
heartbeat
}
```

The results of this query are live-proxied from the underlying subschemas by the stitched gateway:

- `product` comes from the remote Products server. This service is added into the stitched schema using introspection, i.e.: `introspectSchema` from the `@graphql-tools/wrap` package. Introspection is a tidy way to incorporate remote schemas, but be careful: not all GraphQL servers enable introspection, and those that do will not include custom directives.

- `rainforestProduct` also comes from the remote Products server, although here we're pretending it's a third-party API (say, a product database named after a rainforest...). To avoid naming conflicts between our own Products schema and the Rainforest API schema, transforms are used to prefix the names of all types and fields that come from the Rainforest API.

- `storefront` comes from the remote Storefronts server. This service is added to the stitched schema by querying its SDL through its own GraphQL API (very meta). While this is less conventional than introspection, it works with introspection disabled and may include custom directives.

- `errorCodes` comes from a locally-executable schema running on the gateway server itself. This schema is built using `makeExecutableSchema` from the `@graphql-tools/schema` package, and then stitched directly into the combined schema. Note that this still operates as a standalone schema instance that is proxied by the top-level gateway schema.

- `heartbeat` comes from type definitions and resolvers built directly into the gateway proxy layer. This is the only field in this example that returns _directly_ from the gateway schema itself; everything else delegates to an underlying subschema instance.

## Authorization

Authorization is relatively straightforward in a stitched schema; the only trick is that the gateway schema must pass any user authorization information (generally just an `Authorization` header) through to the underlying subservices. This is a two step process:

1) Transfer authorization information from the gateway request into GraphQL context for the request:
## Upload a File

```js
app.use('/graphql', graphqlHTTP((req) => ({
schema,
context: {
authHeader: req.headers.authorization
},
})));
```

2) Add this authorization from context into the executor that builds subschema requests:

```js
function makeRemoteExecutor(url) {
return async ({ document, variables, context }) => {
const query = typeof document === 'string' ? document : print(document);
const fetchResult = await fetch(url, {
method: 'POST',
headers: {
'Authorization': context.authHeader,
'Content-Type': 'application/json',
},
body: JSON.stringify({ query, variables }),
});
return fetchResult.json();
};
};
```
Run the following command from the terminal to upload the file `file.txt`. To learn more, visit [graphql-multipart-request-spec](https://github.com/jaydenseric/graphql-multipart-request-spec)

Also note that this example passes an `adminContext` into all introspection/SDL queries used to fetch remote subschemas. These requests are performed on behalf of the _gateway application_, not any specific user request. Therefore, this administrative context should provide app-to-app credentials on behalf of the gateway.
```bash
curl localhost:4000/graphql \
-F operations='{ "query": "mutation($file: Upload!) { uploadFile(input: $file) { filename mimetype content } }", "variables": { "file": null } }' \
-F map='{ "0": ["variables.file"] }' \
-F 0=@graphql-upload/file.txt

## Error handling

Try fetching a missing record, for example:

```graphql
query {
product(upc: "99") {
upc
name
}
}
# output
# {"data":{"uploadFile":{"filename":"file.txt","mimetype":"text/plain","content":"hello upload\n"}}}
```

You'll recieve a meaningful `NOT_FOUND` error rather than an uncontextualized null response. When building your subservices, always return meaningful errors that can flow through the stitched schema. This becomes particularily important once stitching begins to proxy records across document paths, at which time the confusion of uncontextualized failures will compound. Schema stitching errors are as good as the errors implemented by your subservices.
1 change: 1 addition & 0 deletions graphql-upload/file.txt
@@ -0,0 +1 @@
hello upload
60 changes: 41 additions & 19 deletions graphql-upload/index.js
@@ -1,17 +1,20 @@
const waitOn = require('wait-on');
const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const { introspectSchema } = require('@graphql-tools/wrap');
const { stitchSchemas } = require('@graphql-tools/stitch');
const waitOn = require("wait-on");
const express = require("express");
const { introspectSchema } = require("@graphql-tools/wrap");
const { stitchSchemas } = require("@graphql-tools/stitch");

const makeRemoteExecutor = require('./lib/make_remote_executor');
const localSchema = require('./services/local/schema');
const { GraphQLUpload: GatewayGraphQLUpload } = require("@graphql-tools/links");
const { graphqlUploadExpress } = require("graphql-upload");
const { ApolloServer } = require("apollo-server-express");

const makeRemoteExecutor = require("./lib/make_remote_executor");
const localSchema = require("./services/local/schema");

async function makeGatewaySchema() {
// Make remote executors:
// these are simple functions that query a remote GraphQL API for JSON.
const productsExec = makeRemoteExecutor('http://localhost:4001/graphql');
const adminContext = { authHeader: 'Bearer my-app-to-app-token' };
const productsExec = makeRemoteExecutor("http://localhost:4001/graphql");
const adminContext = { authHeader: "Bearer my-app-to-app-token" };

return stitchSchemas({
subschemas: [
Expand All @@ -27,20 +30,39 @@ async function makeGatewaySchema() {
// No need for a remote executor!
// Note that that the gateway still proxies through
// to this same underlying executable schema instance.
schema: localSchema
}
schema: localSchema,
},
],
resolvers: {
Upload: GatewayGraphQLUpload,
},
});
}


waitOn({ resources: ['tcp:4001'] }, async () => {
async function startApolloServer() {
const schema = await makeGatewaySchema();
const app = express();
app.use('/graphql', graphqlHTTP((req) => ({
const server = new ApolloServer({
schema,
context: { authHeader: req.headers.authorization },
graphiql: true
})));
app.listen(4000, () => console.log('gateway running at http://localhost:4000/graphql'));
uploads: false,
});
await server.start();
const app = express();

// Additional middleware can be mounted at this point to run before Apollo.
app.use(
graphqlUploadExpress({
maxFileSize: 10000000, // 10 MB
maxFiles: 5,
})
);

// Mount Apollo middleware here.
server.applyMiddleware({ app, path: "/", cors: false });

await new Promise((resolve) => app.listen({ port: 4000 }, resolve));
console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`);
}

waitOn({ resources: ["tcp:4001"] }, async () => {
startApolloServer();
});
3 changes: 3 additions & 0 deletions graphql-upload/package.json
Expand Up @@ -9,14 +9,17 @@
"start": "concurrently \"yarn:start-*\""
},
"dependencies": {
"@graphql-tools/links": "^7.1.0",
"@graphql-tools/schema": "^7.0.0",
"@graphql-tools/stitch": "^7.0.4",
"@graphql-tools/wrap": "^7.0.1",
"apollo-server-express": "^2.25.0",
"concurrently": "^5.3.0",
"cross-fetch": "^3.0.6",
"express": "^4.17.1",
"express-graphql": "^0.12.0",
"graphql": "^15.4.0",
"graphql-upload": "^12.0.0",
"nodemon": "^2.0.6",
"wait-on": "^5.2.1"
}
Expand Down
47 changes: 40 additions & 7 deletions graphql-upload/services/local/schema.js
@@ -1,18 +1,51 @@
const { makeExecutableSchema } = require('@graphql-tools/schema');
const { makeExecutableSchema } = require("@graphql-tools/schema");

// does not work
// const { GraphQLUpload } = require("graphql-upload");

// does work
const { GraphQLUpload } =require("@graphql-tools/links");

module.exports = makeExecutableSchema({
typeDefs: `
scalar Upload
type SomeFile {
filename: String
mimetype: String
content: String
}
type Mutation {
uploadFile(input: Upload!): SomeFile!
}
type Query {
errorCodes: [String!]!
}
`,
resolvers: {
Upload: GraphQLUpload,
Mutation: {
uploadFile: async (_, { input }) => {
const { createReadStream, filename, mimetype } = await input;
const chunks = [];
const stream = createReadStream();
for await (const chunk of stream) {
chunks.push(chunk);
}
const buf = Buffer.concat(chunks);

return {
filename,
mimetype,
content: buf.toString(),
};
},
},
Query: {
errorCodes: () => [
'NOT_FOUND',
'GRAPHQL_PARSE_FAILED',
'GRAPHQL_VALIDATION_FAILED',
]
}
}
"NOT_FOUND",
"GRAPHQL_PARSE_FAILED",
"GRAPHQL_VALIDATION_FAILED",
],
},
},
});

0 comments on commit 887c203

Please sign in to comment.