fix sanitizer invalid name

This commit is contained in:
Hongbo Wu 2022-04-13 13:23:21 +08:00
parent 3b831fecb8
commit 8ba1be456c
2 changed files with 17 additions and 11 deletions

View file

@ -5,16 +5,18 @@ import { SanitizedString } from './scalars'
export const sanitizeDirectiveTransformer = (schema: GraphQLSchema) => {
return mapSchema(schema, {
[MapperKind.FIELD]: (fieldConfig) => {
const sanitizeDirective = getDirective(schema, fieldConfig, 'sanitize')
if (!sanitizeDirective || sanitizeDirective.length < 1) {
const sanitizeDirective = getDirective(
schema,
fieldConfig,
'sanitize'
)?.[0]
if (!sanitizeDirective) {
return fieldConfig
}
const maxLength = sanitizeDirective[0].maxLength as number | undefined
const allowedTags = sanitizeDirective[0].allowedTags as
| string[]
| undefined
const pattern = sanitizeDirective[0].pattern as RegExp | undefined
const maxLength = sanitizeDirective.maxLength as number | undefined
const allowedTags = sanitizeDirective.allowedTags as string[] | undefined
const pattern = sanitizeDirective.pattern as string | undefined
if (
fieldConfig.type instanceof GraphQLNonNull &&

View file

@ -9,10 +9,14 @@ export class SanitizedString extends GraphQLScalarType {
type: GraphQLScalarType,
allowedTags?: string[],
maxLength?: number,
pattern?: RegExp
pattern?: string
) {
super({
name: `SanitizedString_${allowedTags}_${maxLength}_${pattern}`,
// Names must match /^[_a-zA-Z][_a-zA-Z0-9]*$/ as per graphql-js
name: `SanitizedString_${allowedTags}_${maxLength}_${pattern}`.replace(
/\W/g,
''
),
description: 'Source string that was sanitized',
serialize(value: string) {
@ -26,7 +30,7 @@ export class SanitizedString extends GraphQLScalarType {
`Specified value cannot be longer than ${maxLength} characters`
)
}
if (pattern && !pattern.test(value)) {
if (pattern && !new RegExp(pattern).test(value)) {
throw new Error(`Specified value does not match pattern`)
}
return sanitize(value, { allowedTags: allowedTags || [] })
@ -40,7 +44,7 @@ export class SanitizedString extends GraphQLScalarType {
`Specified value cannot be longer than ${maxLength} characters`
)
}
if (pattern && !pattern.test(value)) {
if (pattern && !new RegExp(pattern).test(value)) {
throw new Error(`Specified value does not match pattern`)
}
return sanitize(value, { allowedTags: allowedTags || [] })