graphql-generator-typescript v1.0.8
graphql-generator-typescript
Generate queries from graphql schema in typescript wrapped in graphql-tags.
Usage
# Install
yarn add gql-generator-typescript
or
npm i gql-generator-typescript
# see the usage
gqlgen --help
# Generate sample queries from typeDefs
gqlgen --schemaFilePath ./example/sampleTypeDef.graphql --destDirPath ./example/output
Now you can find the generated queries in the destDir: ./example/output
.
# Sample schema
type Query {
user(id: Int!): User!
}
type User {
id: Int!
username: String!
email: String!
createdAt: String!
}
# Sample query generated
import gql from 'graphql-tag';
export const user = gql`
query user($id: Int!)
{
user(id: $id){
id
username
email
createdAt
}
}`;
This tool will generate 3 folders holding the queries: mutations, queries and subscriptions. And generate a index.ts
exports the queries in each folder.
Also another index.ts
is generated in the root destPath
to export all the queries (you can look into the example folder for details of generated files).
After generating the queries, you can require them like this:
Sample result:
The output
folder inside example
folder is generated from the sampleTypeDef.graphql
by this command:
gqlg --schemaFilePath ./example/sampleTypeDef.graphql --destDirPath ./example/output
Usage example
Say you have a graphql schema like this:
type Mutation {
signup(
email: String!
username: String!
password: String!
): UserToken!
}
type UserToken {
token: String!
user: User!
}
type User {
id: Int!
username: String!
email: String!
createdAt: String!
}
As gqlgen
generated the queries for you, you don't need to write the query yourself:
const { GraphQLClient } = require('graphql-request');
require('should');
const mutations = require('./example/output/mutations');
const host = 'http://localhost:8080/graphql';
test('signup', async () => {
const gql = new GraphQLClient(host);
const data = await gql.request(mutations.signup, {
username: 'tim',
email: 'timqian92@qq.com',
password: 'samplepass',
});
(typeof data.signup.token).should.equal('string');
);
Thanks
Notice
As this tool is used for test, it expends all the fields in a query. And as we know, there might be recursive field in the query. So gqlg
ignores the types which has been added in the parent queries already.