-
-
Notifications
You must be signed in to change notification settings - Fork 221
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Example: how to create dedicated email and URL types #109
Open
singingwolfboy
wants to merge
2
commits into
graphile:main
Choose a base branch
from
singingwolfboy:url-type
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
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
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
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
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
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
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
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,149 @@ | ||
import { Plugin, Build, ScopeGraphQLScalarType } from "graphile-build"; | ||
import { PgType } from "graphile-build-pg"; | ||
|
||
declare module "graphile-build" { | ||
interface ScopeGraphQLScalarType { | ||
isEmailScalar?: boolean; | ||
} | ||
} | ||
|
||
function isValidEmail(email: string) { | ||
return /[^@]+@[^@]+\.[^@]+/.test(email); | ||
} | ||
|
||
export default (function PgTypeEmailPlugin(builder) { | ||
builder.hook( | ||
"build", | ||
build => { | ||
// This hook tells graphile-build-pg about the email database type so it | ||
// knows how to express it in input/output. | ||
const { | ||
pgIntrospectionResultsByKind: rawIntrospectionResultsByKind, | ||
pgRegisterGqlTypeByTypeId, | ||
pgRegisterGqlInputTypeByTypeId, | ||
pg2GqlMapper, | ||
pgSql: sql, | ||
} = build; | ||
|
||
if ( | ||
!rawIntrospectionResultsByKind || | ||
!sql || | ||
!pgRegisterGqlTypeByTypeId || | ||
!pgRegisterGqlInputTypeByTypeId || | ||
!pg2GqlMapper | ||
) { | ||
throw new Error("Required helpers were not found on Build."); | ||
} | ||
|
||
const introspectionResultsByKind = rawIntrospectionResultsByKind; | ||
|
||
// Get the 'email' type: | ||
const emailType = introspectionResultsByKind.type.find( | ||
(t: PgType) => t.name === "email" | ||
); | ||
|
||
if (!emailType) { | ||
return build; | ||
} | ||
|
||
const emailTypeName = build.inflection.builtin("Email"); | ||
|
||
const GraphQLEmailType = makeGraphQLEmailType( | ||
build as Build, | ||
emailTypeName | ||
); | ||
|
||
// Now register the Email type with the type system for both output and input. | ||
pgRegisterGqlTypeByTypeId(emailType.id, () => GraphQLEmailType); | ||
pgRegisterGqlInputTypeByTypeId(emailType.id, () => GraphQLEmailType); | ||
|
||
// Finally we must tell the system how to translate the data between PG-land and JS-land: | ||
pg2GqlMapper[emailType.id] = { | ||
// Turn string (from node-postgres) into email: no-op | ||
map: (email: string) => email, | ||
// When unmapping we need to convert back to SQL framgent | ||
unmap: (email: string) => | ||
sql.fragment`(${sql.value(email)}::${sql.identifier( | ||
emailType.namespaceName, | ||
emailType.name | ||
)})`, | ||
}; | ||
|
||
return build; | ||
}, | ||
["PgTypeEmail"], | ||
[], | ||
["PgTypes"] | ||
); | ||
|
||
/* End of email type */ | ||
} as Plugin); | ||
|
||
function makeGraphQLEmailType(build: Build, emailTypeName: string) { | ||
const { | ||
graphql: { GraphQLScalarType, Kind }, | ||
} = build; | ||
function parseValue(obj: unknown): string { | ||
if (!(typeof obj === "string")) { | ||
throw new TypeError( | ||
`This is not a valid ${emailTypeName} object, it must be a string.` | ||
); | ||
} | ||
if (!isValidEmail(obj)) { | ||
throw new TypeError( | ||
`This is not a properly formatted ${emailTypeName} object.` | ||
); | ||
} | ||
return obj; | ||
} | ||
|
||
const parseLiteral: import("graphql").GraphQLScalarLiteralParser<any> = ( | ||
ast, | ||
variables | ||
) => { | ||
switch (ast.kind) { | ||
case Kind.STRING: { | ||
const email = ast.value; | ||
if (!isValidEmail(email)) { | ||
throw new TypeError( | ||
`This is not a properly formatted ${emailTypeName} object.` | ||
); | ||
} | ||
return email; | ||
} | ||
|
||
case Kind.NULL: | ||
return null; | ||
|
||
case Kind.VARIABLE: { | ||
const name = ast.name.value; | ||
const email = variables ? variables[name] : undefined; | ||
if (!isValidEmail(email)) { | ||
throw new TypeError( | ||
`This is not a properly formatted ${emailTypeName} object.` | ||
); | ||
} | ||
return email; | ||
} | ||
|
||
default: | ||
return undefined; | ||
} | ||
}; | ||
|
||
const scope: ScopeGraphQLScalarType = { isEmailScalar: true }; | ||
const GraphQLEmailType = build.newWithHooks( | ||
GraphQLScalarType, | ||
{ | ||
name: emailTypeName, | ||
description: | ||
"An address in the electronic mail system. Email addresses such as `[email protected]` are made up of a local-part, followed by an `@` symbol, followed by a domain.", | ||
serialize: (email: string) => email, | ||
parseValue, | ||
parseLiteral, | ||
}, | ||
scope | ||
); | ||
|
||
return GraphQLEmailType; | ||
} | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@singingwolfboy It seems to me that this plugin adds the
Email
type, with a comment, and performs validation on it. However we already perform validation on the type using the domain constraint you added; so I'm not sure if these 149 lines of code add much additional value? If this plugin were removed, would the following be sufficient?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
As I mentioned in the description of the pull request, the benefit of making an
Email
GraphQL scalar is that anyone introspecting the schema knows that the corresponding field won't accept just any string: it must be a valid email address. You're correct that this was already enforced at the database level, but because it wasn't exposed at the schema level, it could cause surprises. Using anEmail
scalar is a fairly trivial example, but consider that this repo is also meant to be an example of how to do things with PostGraphile: I think that learning how to create your own GraphQL scalar with PostGraphile is very useful!For a more concrete example of how this could be useful, consider a front-end application that you can point at an arbitrary GraphQL schema, and it can generate a pretty HTML form for doing queries and mutations on that schema. Because it needs to work with arbitrary schemas, it can't have much knowledge about the structure of the schema that it's going to see: as a result, it makes sense to have this application look at the scalars in the schema, and generate form fields based on that. If we expose the
User.email
field as typeString
, this application could only generate a standard text field; but if we expose it as typeEmail
, it could style the field differently and provide dynamic validation based on how emails are formatted.There's a section in the Shopify GraphQL Design Tutorial about naming and scalars, which I think is relevant here. Semantic value can be really useful for GraphQL clients, so I think it makes sense to expose that semantic value as clearly as possible.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I’m cool with the custom scalar and totally understand the reasoning; for some reason I was expecting creating a custom domain to result in a custom scalar being created. Seems maybe I never implemented that https://github.com/graphile/graphile-engine/blob/v4/packages/graphile-build-pg/src/plugins/PgTypesPlugin.js#L844