Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

mercurius

Package Overview
Dependencies
Maintainers
2
Versions
116
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

mercurius - npm Package Compare versions

Comparing version 13.1.0 to 13.2.0

22

docs/api/options.md

@@ -557,1 +557,23 @@ # mercurius

```
Using the errorFormatter means overriding the `defaultErrorFormatter` and it could cause ambiguous GraphQL error message like `GraphQL validation error` without indicating where and why the error happens. To retain the default error behaviour, you can reimplement the `defaultErrorFormatter`.
```javascript
import mercurius from 'mercurius';
const { defaultErrorFormatter } = mercurius;
app.register(mercurius, {
schema,
resolvers,
errorFormatter: (result, context) => {
const formatter = defaultErrorFormatter(result, context);
// your custom behaviour here
return {
statusCode: formatter.statusCode || 500,
response: formatter.response,
};
},
});
```

98

docs/custom-directive.md

@@ -59,6 +59,6 @@ # Custom directive

const redactionSchemaTransformer = (schema) =>
const redactionSchemaTransformer = schema =>
mapSchema(schema, {
// When parsing the schema we find a FIELD
[MapperKind.FIELD]: (fieldConfig) => {
[MapperKind.FIELD]: fieldConfig => {
// Get the directive information

@@ -81,3 +81,3 @@ const redactDirective = getDirective(schema, fieldConfig, "redact")?.[0];

case "phone":
return value.replace(PHONE_REGEXP, (m) => "*".repeat(m.length));
return value.replace(PHONE_REGEXP, m => "*".repeat(m.length));
default:

@@ -132,1 +132,93 @@ return value;

We have a runnable example on "example/custom-directive.js"
## Federation and Custom Directives
Because schemas involved in GraphQL federation may use special syntax (e.g. `extends`) and custom directives (e.g. `@key`) that are not available in non-federated schemas, there are some extra steps that need to be run to generate the executable schema, involving the use of `buildFederationSchema` from the `@mercuriusjs/federation` library and `printSchemaWithDirectives` from the `@graphql-tools/utils` library.
To see how this works, we will go through another example where we create a custom directive to uppercase the value of a field in a federated environment.
### Schema Definition
The schema definition is equal to the one used in the previous example. We add the `@upper` directive and we decorate the `name` field with it.
```js
const schema = `
directive @upper on FIELD_DEFINITION
extend type Query {
me: User
}
type User @key(fields: "id") {
id: ID!
name: String @upper
username: String
}`;
```
### Transformer
The transformer follows the same approach used in the previous example. We declare the uppercase transform function and apply it to the field resolver if they have the `@upper` directive.
```js
const { mapSchema, getDirective, MapperKind } = require("@graphql-tools/utils");
const uppercaseTransformer = schema =>
mapSchema(schema, {
[MapperKind.FIELD]: fieldConfig => {
const upperDirective = getDirective(schema, fieldConfig, "upper")?.[0];
if (upperDirective) {
fieldConfig.resolve = async (obj, _args, _ctx, info) => {
const value = obj[info.fieldName];
return typeof value === "string" ? value.toUpperCase() : value;
};
}
},
});
```
### Generate executable schema
This section starts to be different. First, we need to create the federation schema using the `buildFederationSchema` function from the `@mercuriusjs/federation` library; then, we can use the `makeExecutableSchema` function from the `@graphql-tools/schema` library to create the executable schema.
Using the `printSchemaWithDirectives`, we can get the schema with all the custom directives applied, and using the `mergeResolvers` function from the `@graphql-tools/merge` library, we can merge the resolvers from the federation schema and the ones we defined.
Following these steps, we can create our executable schema.
```js
const { buildFederationSchema } = require("@mercuriusjs/federation");
const {
printSchemaWithDirectives,
getResolversFromSchema,
} = require("@graphql-tools/utils");
const { mergeResolvers } = require("@graphql-tools/merge");
const { makeExecutableSchema } = require("@graphql-tools/schema");
const federationSchema = buildFederationSchema(schema);
const executableSchema = makeExecutableSchema({
typeDefs: printSchemaWithDirectives(federationSchema),
resolvers: mergeResolvers([
getResolversFromSchema(federationSchema),
resolvers,
]),
});
```
### Apply transformations to the executable schema
To apply the transformation, we have to use the mercurius plugin and pass the options:
- **schema**: with the executableSchema already generated
- **schemaTransforms**: with the transformer functions
```js
app.register(mercurius, {
schema: executableSchema,
schemaTransforms: [uppercaseTransformer],
graphiql: true,
});
```
### Example
We have a runnable example in the Federation repo that you can find here [examples/withCustomDirectives.js](https://github.com/mercurius-js/mercurius-federation/tree/main/examples/withCustomDirectives.js).

7

lib/subscriber.js

@@ -28,3 +28,4 @@ 'use strict'

})
queue.close = close
if (!queue.close) queue.close = []
queue.close.push(close)
})

@@ -72,4 +73,4 @@ }

// `close` will be `undefined`.
if (typeof this.queue.close === 'function') {
this.queue.close()
if (Array.isArray(this.queue.close)) {
this.queue.close.map((close) => close())
}

@@ -76,0 +77,0 @@ this.queue.push(null)

{
"name": "mercurius",
"version": "13.1.0",
"version": "13.2.0",
"description": "Fastify GraphQL adapter with subscription support",

@@ -51,3 +51,3 @@ "main": "index.js",

"semver": "^7.5.0",
"sinon": "^15.0.0",
"sinon": "^16.0.0",
"snazzy": "^9.0.0",

@@ -57,3 +57,3 @@ "split2": "^4.0.0",

"tap": "^16.3.0",
"tsd": "^0.28.0",
"tsd": "^0.29.0",
"typescript": "^5.0.2",

@@ -60,0 +60,0 @@ "wait-on": "^7.0.1"

@@ -100,8 +100,13 @@ /* global React:false ReactDOM:false GraphiQL:false */

const host = window.location.host
const websocketProtocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
let url = ''
let subscriptionUrl = ''
if (window.baseurl) {
url = `${window.location.protocol}//${host}${window.baseurl}${window.GRAPHQL_ENDPOINT}`
subscriptionUrl = `${websocketProtocol}//${host}${window.baseurl}${window.GRAPHQL_ENDPOINT}`
} else {
url = `${window.location.protocol}//${host}${window.GRAPHQL_ENDPOINT}`
subscriptionUrl = `${websocketProtocol}//${host}${window.GRAPHQL_ENDPOINT}`
}
const url = `${window.location.protocol}//${host}${window.GRAPHQL_ENDPOINT}`
const subscriptionUrl = `${websocketProtocol}//${host}${window.GRAPHQL_ENDPOINT}`
const availablePlugins = window.GRAPHIQL_PLUGIN_LIST

@@ -108,0 +113,0 @@ .map(plugin => window[`GRAPIHQL_PLUGIN_${plugin.toUpperCase()}`])

@@ -81,5 +81,6 @@ const { test } = require('tap')

test('subscription context can handle multiple topics', t => {
t.plan(2)
t.plan(4)
const pubsub = new PubSub(mq())
const q = mq()
const pubsub = new PubSub(q)
const sc = new SubscriptionContext({ pubsub })

@@ -100,2 +101,6 @@

})
t.equal(q._matcher._trie.size, 2, 'Two listeners not found')
sc.close()
setImmediate(() => { t.equal(q._matcher._trie.size, 0, 'All listeners not removed') })
})

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc