-
Notifications
You must be signed in to change notification settings - Fork 44
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(apollo-mock-server): introduce package
- Loading branch information
1 parent
d3d399c
commit 10b9ba0
Showing
6 changed files
with
314 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,126 @@ | ||
# `hops-apollo-mock-server` | ||
|
||
[![npm](https://img.shields.io/npm/v/hops-apollo-mock-server.svg)](https://www.npmjs.com/package/hops-apollo-mock-server) | ||
|
||
**Please see the [main Hops Readme](https://github.com/xing/hops/blob/master/README.md) for general information and a Getting Started Guide.** | ||
|
||
This is a [preset for Hops](https://github.com/xing/hops/tree/master#presets) in order to start and configure an Apollo Server that can be used for GraphQL mocking to enable faster local development. | ||
|
||
### Installation | ||
|
||
Add this preset and its peer dependency `graphql-tag` to your existing Hops React project: | ||
|
||
```bash | ||
npm install --save hops-apollo-mock-server graphql-tag | ||
``` | ||
|
||
If you don't already have an existing Hops project read this section [on how to set up your first Hops project.](https://github.com/xing/hops/tree/master#quick-start) | ||
|
||
### Usage | ||
|
||
#### Creating custom mocks and stitching schemas using Apollo Server | ||
|
||
When you are using GraphQL on client side to fetch and bind data into your UI components, it's quite often necessary to work with mock/stub data. There exists tons of feasible reasons why mocking makes sense in daily practices. In summary, the following seem to be the most important. | ||
|
||
- GraphQL schema design in a Frontend-Driven approach | ||
- Switching between local and remote query execution to work autonomously without an online GraphQL-Server access | ||
- Faster execution of component integration test using local mock data sets | ||
- Mock data set support to prove experimental/feature functionality thesis | ||
|
||
You can enable mocking by configuring a file that exports an executable schema. Read more about [schema stitching](https://www.apollographql.com/docs/graphql-tools/schema-stitching.html) and check out [this blog post](https://blog.hasura.io/the-ultimate-guide-to-schema-stitching-in-graphql-f30178ac0072) for more examples. | ||
|
||
**Supports Local GraphQL Playground against your GraphQL schema** | ||
|
||
`open http://localhost:<port>/graphql` | ||
|
||
![GraphiQL Playground](./playground.png) | ||
|
||
### Configuration | ||
|
||
#### Preset Options | ||
|
||
| Name | Type | Default | Required | Description | | ||
| --- | --- | --- | --- | --- | | ||
| `fragmentsFile` | `String` | `<rootDir>/fragmentTypes.json` | _no_ | Where to store the generated fragment types file | | ||
| `graphqlUri` | `String` | `''` | _yes_ | Url to your GraphQL endpoint or mock server | | ||
| `graphqlSchemaFile` | `String` | `''` | _no_ | Path to your GraphQL schema file | | ||
| `graphqlMockSchemaFile` | `String` | `''` | _no_ | Path to your GraphQL schema mocks | | ||
| `graphqlMockServerPath` | `String` | `'/graphql'` | _no_ | Path of the mock server endpoint | | ||
|
||
##### `fragmentsFile` | ||
|
||
This option controls where the fragment type information that are used for the `IntrospectionFragmentMatcher` should be saved. | ||
|
||
By default executing `$ hops graphql introspect` will create a file called `fragmentTypes.json` in the application root directory. | ||
|
||
```json | ||
"hops": { | ||
"fragmentsFile": "<rootDir>/fragmentTypes.json" | ||
} | ||
``` | ||
|
||
##### `graphqlUri` | ||
|
||
This is the full URI to your GraphQL endpoint which should be used by the client- and server-side when executing requests. | ||
|
||
This will also be used to generate fragment type information with `$ hops graphql introspect` in case no [`graphqlSchemaFile`](#graphqlschemafile) has been provided. | ||
|
||
```json | ||
"hops": { | ||
"graphqlUri": "https://www.graphqlhub.com/graphql" | ||
} | ||
``` | ||
|
||
##### `graphqlSchemaFile` | ||
|
||
In case your GraphQL server (configured via [`graphqlUri`](#graphqluri)) does not answer to introspection queries, you can provide the full schema as a file from which the introspection fragment matcher can generate information about unions and interfaces. | ||
|
||
```json | ||
"hops": { | ||
"graphqlSchemaFile": "<rootDir>/schema.graphql" | ||
} | ||
``` | ||
|
||
##### `graphqlMockSchemaFile` | ||
|
||
Specify the path to your stitched mock schema, which is a file that exports an executable schema or a promise that resolves to an executable schema. | ||
|
||
```json | ||
{ | ||
"hops": { | ||
"graphqlMockSchemaFile": "<rootDir>/graphql/index.js" | ||
} | ||
} | ||
``` | ||
|
||
**Example mock schema: `graphql/index.js`** | ||
|
||
```javascript | ||
import { makeExecutableSchema, addMockFunctionsToSchema } from 'graphql-tools'; | ||
import merge from 'lodash.merge'; | ||
|
||
import schema1 from './schema1.graphql'; | ||
import schema2 from './schema2.graphql'; | ||
|
||
import resolvers1 from './resolvers1'; | ||
import resolvers2 from './resolvers2'; | ||
|
||
const typeDefs = [schema1, schema2]; | ||
|
||
const resolvers = merge(resolvers1, resolvers2); | ||
|
||
const mockSchema = makeExecutableSchema({ | ||
typeDefs, | ||
resolvers, | ||
}); | ||
|
||
addMockFunctionsToSchema({ | ||
schema: mockSchema, | ||
mocks: { | ||
Date: () => '2017-10-17T13:06:22Z', | ||
}, | ||
preserveResolvers: true, | ||
}); | ||
|
||
export default mockSchema; | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
import { ApolloServer } from 'apollo-server-express'; | ||
import cookieParser from 'cookie-parser'; | ||
import express from 'express'; | ||
import hopsConfig from 'hops-config'; | ||
// eslint-disable-next-line node/no-extraneous-import | ||
import schema from 'hops-apollo-mock-server/schema'; | ||
|
||
const apolloAppPromise = Promise.resolve( | ||
typeof schema === 'function' ? schema() : schema | ||
).then(resolvedSchema => { | ||
const app = express(); | ||
app.use(cookieParser()); | ||
|
||
const server = new ApolloServer({ | ||
schema: resolvedSchema, | ||
playground: { | ||
settings: { | ||
'request.credentials': 'same-origin', | ||
}, | ||
}, | ||
context: context => ({ ...context, config: hopsConfig }), | ||
}); | ||
|
||
server.applyMiddleware({ | ||
app, | ||
path: hopsConfig.graphqlMockServerPath, | ||
cors: { | ||
credentials: true, | ||
origin: true, | ||
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE', | ||
allowedHeaders: 'content-type', | ||
}, | ||
}); | ||
|
||
return app; | ||
}); | ||
|
||
export default (req, res, next) => { | ||
apolloAppPromise.then(app => app.handle(req, res, next), next); | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,84 @@ | ||
const { existsSync } = require('fs'); | ||
const { Mixin } = require('hops-mixin'); | ||
const { | ||
internal: { createWebpackMiddleware, StatsFilePlugin }, | ||
} = require('@untool/webpack'); | ||
|
||
function exists(path) { | ||
try { | ||
require.resolve(path); | ||
return true; | ||
} catch (e) { | ||
return false; | ||
} | ||
} | ||
|
||
class GraphQLMixin extends Mixin { | ||
configureServer(rootApp, middleware, mode) { | ||
if ( | ||
!exists(this.config.graphqlMockSchemaFile) || | ||
process.env.NODE_ENV === 'production' | ||
) { | ||
return; | ||
} | ||
|
||
middleware.initial.push({ | ||
path: this.config.graphqlMockServerPath, | ||
handler: createWebpackMiddleware( | ||
['graphql-mock-server', 'node'], | ||
mode === 'develop', | ||
this | ||
), | ||
}); | ||
} | ||
|
||
configureBuild(webpackConfig, loaderConfigs, target) { | ||
const { allLoaderConfigs } = loaderConfigs; | ||
|
||
allLoaderConfigs.splice(allLoaderConfigs.length - 1, 0, { | ||
test: /\.(graphql|gql)$/, | ||
loader: 'graphql-tag/loader', | ||
}); | ||
|
||
webpackConfig.externals.push('encoding'); | ||
|
||
if (process.env.NODE_ENV === 'production') { | ||
return; | ||
} | ||
|
||
if (exists(this.config.graphqlMockSchemaFile)) { | ||
webpackConfig.resolve.alias[ | ||
'hops-apollo-mock-server/schema' | ||
] = require.resolve(this.config.graphqlMockSchemaFile); | ||
} | ||
|
||
if (target === 'graphql-mock-server') { | ||
webpackConfig.externals.push( | ||
'apollo-server-express', | ||
'express', | ||
'graphql' | ||
); | ||
|
||
webpackConfig.output.filename = 'hops-graphql-mock-server.js'; | ||
webpackConfig.resolve.alias['@untool/entrypoint'] = require.resolve( | ||
'./lib/mock-server-middleware' | ||
); | ||
|
||
webpackConfig.plugins = webpackConfig.plugins.filter( | ||
p => !(p instanceof StatsFilePlugin) | ||
); | ||
} | ||
} | ||
|
||
diagnose({ detectDuplicatePackages }) { | ||
detectDuplicatePackages('graphql'); | ||
if (!existsSync(this.config.fragmentsFile)) { | ||
return [ | ||
`Could not find a graphql introspection query result at "${this.config.fragmentsFile}".`, | ||
'You might need to execute "hops graphql introspect"', | ||
]; | ||
} | ||
} | ||
} | ||
|
||
module.exports = GraphQLMixin; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
{ | ||
"name": "hops-apollo-mock-server", | ||
"version": "12.0.0-alpha.3", | ||
"description": "Apollo based mock server for Hops", | ||
"keywords": [ | ||
"hops", | ||
"apollo", | ||
"graphql", | ||
"mock-server", | ||
"unpreset", | ||
"unmixin" | ||
], | ||
"license": "MIT", | ||
"engines": { | ||
"node": "^10 || ^12" | ||
}, | ||
"repository": { | ||
"type": "git", | ||
"url": "https://github.com/xing/hops.git" | ||
}, | ||
"dependencies": { | ||
"@untool/webpack": "^2.0.0-alpha.4", | ||
"apollo-cache-inmemory": "^1.6.3", | ||
"apollo-server-express": "^2.9.5", | ||
"cookie-parser": "^1.4.4", | ||
"cross-fetch": "^3.0.4", | ||
"express": "^4.17.1", | ||
"graphql": "^14.5.8", | ||
"graphql-tools": "^4.0.5", | ||
"hops-config": "^12.0.0-alpha.3", | ||
"hops-mixin": "^12.0.0-alpha.3" | ||
}, | ||
"peerDependencies": { | ||
"graphql-tag": "^2.10.0" | ||
}, | ||
"devDependencies": { | ||
"graphql-tag": "^2.10.1" | ||
}, | ||
"homepage": "https://github.com/xing/hops/tree/master/packages/graphql#readme" | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
module.exports = { | ||
mixins: [__dirname], | ||
fragmentsFile: '<rootDir>/fragmentTypes.json', | ||
graphqlMockServerPath: '/graphql', | ||
configSchema: { | ||
fragmentsFile: { | ||
type: 'string', | ||
absolutePath: true, | ||
}, | ||
graphqlSchemaFile: { | ||
type: 'string', | ||
absolutePath: true, | ||
}, | ||
graphqlMockSchemaFile: { | ||
type: 'string', | ||
}, | ||
graphqlMockServerPath: { | ||
type: 'string', | ||
}, | ||
}, | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
throw new Error( | ||
'Please use an absolute path for setting "config.graphqlMockSchemaFile", like e.g. "<rootDir>/schema.js".' | ||
); |