Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to alias a type (e.g. string, int...)

Tags:

graphql

I know from the doc I can alias a field. But how could I alias a type?

E.g. how could I alias a int or string type? Will type MyStringType = String work?

Motivation

I have a signin mutation that returns an auth token, and I would like to write something like:

type Mutation {
    signin(email: String!, password: String!): AuthToken
}
type AuthToken = String
like image 515
Lucas Willems Avatar asked Sep 21 '25 12:09

Lucas Willems


1 Answers

GraphQL does not support type aliases.

You can, however, implement a custom scalar with the same properties as an existing scalar but a different name. It's unclear from your question what language or libraries you're working with, but in GraphQL.js, you can just do something like:

const { GraphQLString, GraphQLScalarType } = require('graphql')
const AuthToken = new GraphQLScalarType({
  name: 'AuthToken',
  description: 'Your description here',
  serialize: GraphQLString.serialize,
  parseValue: GraphQLString.parseValue,
  parseLiteral: GraphQLString.parseLiteral,
})

Here's how to add a custom scalar in Apollo Server. Keep in mind that doing this may actually make things harder for clients, especially ones written in strongly typed languages. If you don't need custom serialization or parsing behavior, I would stick to the built-in scalars.

like image 75
Daniel Rearden Avatar answered Sep 23 '25 10:09

Daniel Rearden