https://github.com/akryum/graphql-annotations
Annotate a GraphQL schema
https://github.com/akryum/graphql-annotations
Last synced: over 1 year ago
JSON representation
Annotate a GraphQL schema
- Host: GitHub
- URL: https://github.com/akryum/graphql-annotations
- Owner: Akryum
- License: mit
- Created: 2019-01-29T12:28:21.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2021-08-03T19:19:26.000Z (almost 5 years ago)
- Last Synced: 2025-02-28T18:57:03.997Z (over 1 year ago)
- Language: JavaScript
- Size: 563 KB
- Stars: 17
- Watchers: 3
- Forks: 0
- Open Issues: 14
-
Metadata Files:
- Readme: README.md
- Funding: .github/FUNDING.yml
- License: LICENSE
Awesome Lists containing this project
README
# graphql-annotations
[](https://circleci.com/gh/Akryum/graphql-annotations)
Annotate a GraphQL schema
## Sponsors
### Gold
### Silver
### Bronze
## Installation
```bash
npm i graphql-annotations
```
## Usage
### Annotations parsing
Here is a very basic example with a `namespace` (here `'db'`) and a `description` that needs to be parsed:
```js
const { parseAnnotations } = require('graphql-annotations')
const result = parseAnnotations('db', `
This is a description
@db.length: 200
@db.foo: 'bar'
@db.unique
@db.index: { name: 'foo', type: 'string' }
`)
console.log(result)
```
This will output an object containing the annotations:
```js
{
length: 200,
foo: 'bar',
unique: true,
index: { name: 'foo', type: 'string' }
}
```
In a GraphQL schema, you can use the `description` property on `GraphQLObjectType`, `GraphQLField`...
```js
const { parseAnnotations } = require('graphql-annotations')
const { buildSchema, isObjectType } = require('graphql')
const schema = buildSchema(`
"""
@db.table: 'users'
"""
type User {
"""
@db.primary
"""
id: ID!
}
`)
const typeMap = schema.getTypeMap()
for (const key in typeMap) {
const type = typeMap[key]
// Tables
if (isObjectType(type)) {
const typeAnnotations = parseAnnotations('db', type.description)
console.log(type.name, typeAnnotations)
const fields = type.getFields()
for (const key in fields) {
const field = fields[key]
const fieldAnnotations = parseAnnotations('db', field.description)
console.log(field.name, fieldAnnotations)
}
}
}
```
Which will output:
```js
User { table: 'users' }
id { primary: true }
```
### Strip annotations
Sometimes it will be helpful to strip the annotations from the description. For example, you may not want to display them in a GraphQL schema explorer.
```js
const { stripAnnotations } = require('graphql-annotations')
const result = stripAnnotations('db', `
This is a description
@db.length: 200
@db.foo: 'bar'
@db.unique
@db.index: { name: 'foo', type: 'string' }
`)
console.log(result)
```
The result will be:
```js
`
This is a description
`
```