graphql#GraphQLScalarType TypeScript Examples
The following examples show how to use
graphql#GraphQLScalarType.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: utils.ts From tql with MIT License | 7 votes |
printType = (type: GraphQLNamedType) => {
if (type instanceof GraphQLScalarType) {
return `${type.name}: ${toPrimitive(type)}`;
} else if (type instanceof GraphQLEnumType) {
return `${type.name}: ${type.name}`;
} else {
return `${type.name}: I${type.name}`;
}
}
Example #2
Source File: utils.ts From tql with MIT License | 7 votes |
toPrimitive = (
scalar: GraphQLScalarType
): "number" | "string" | "boolean" => {
switch (scalar.name) {
case "ID":
case "String":
return "string";
case "Boolean":
return "boolean";
case "Int":
case "Float":
return "number";
default:
return "string";
}
}
Example #3
Source File: helpers.ts From amplify-codegen with Apache License 2.0 | 6 votes |
typeNameForScalarType(type: GraphQLScalarType): string {
return (
builtInScalarMap[type.name] ||
(this.options.passthroughCustomScalars
? this.options.customScalarsPrefix + type.name
: getTypeForAWSScalar(type)
? getTypeForAWSScalar(type)
: GraphQLString.name)
);
}
Example #4
Source File: custom-date.scalar.ts From Cromwell with MIT License | 6 votes |
CustomDateScalar = new GraphQLScalarType({
name: "CustomDateScalar",
description: "Custom implementation of Date scalar",
parseValue(value: string) {
try {
return new Date(value);
} catch (error) { }
return null;
},
serialize(value: Date) {
try {
return value.toISOString()
} catch (e) { }
return null;
},
parseLiteral(ast) {
if (ast.kind === Kind.STRING) {
return new Date(ast.value);
}
if (ast.kind === Kind.INT) {
return new Date(parseInt(ast.value, 10));
}
return null;
},
})
Example #5
Source File: helpers.ts From amplify-codegen with Apache License 2.0 | 6 votes |
fieldTypeEnum(type: GraphQLType, structName: string): string {
if (isNonNullType(type)) {
return `.nonNull(${this.fieldTypeEnum(type.ofType, structName)})`;
} else if (isListType(type)) {
return `.list(${this.fieldTypeEnum(type.ofType, structName)})`;
} else if (type instanceof GraphQLScalarType) {
return `.scalar(${this.typeNameForScalarType(type)}.self)`;
} else if (type instanceof GraphQLEnumType) {
return `.scalar(${type.name}.self)`;
} else if (isCompositeType(type)) {
return `.object(${structName}.selections)`;
} else {
throw new Error(`Unknown field type: ${type}`);
}
}
Example #6
Source File: types.ts From amplify-codegen with Apache License 2.0 | 6 votes |
export function typeNameFromGraphQLType(
context: LegacyCompilerContext,
type: GraphQLType,
bareTypeName?: string | null,
nullable = true
): string {
if (isNonNullType(type)) {
return typeNameFromGraphQLType(context, type.ofType, bareTypeName, false);
}
let typeName;
if (isListType(type)) {
typeName = `Array< ${typeNameFromGraphQLType(context, type.ofType, bareTypeName, true)} >`;
} else if (type instanceof GraphQLScalarType) {
typeName =
builtInScalarMap[type.name] ||
appSyncScalars[type.name] ||
(context.options.passthroughCustomScalars ? context.options.customScalarsPrefix + type.name : builtInScalarMap[GraphQLString.name]);
} else {
typeName = bareTypeName || type.name;
}
return nullable ? typeName + ' | null' : typeName;
}
Example #7
Source File: Writer.ts From graphql-ts-client with MIT License | 6 votes |
protected importType(type: GraphQLType) {
if (this.imported) {
throw new Error("Writer's importing has been terminated");
}
if (type instanceof GraphQLNonNull) {
this.importType(type.ofType);
} else if (type instanceof GraphQLList) {
this.importType(type.ofType);
} else if (type instanceof GraphQLInputObjectType) {
this.importedTypes.add(type);
} else if (type instanceof GraphQLEnumType) {
this.importedTypes.add(type);
} else if (type instanceof GraphQLScalarType && this.config.scalarTypeMap !== undefined) {
const mappedType = this.config.scalarTypeMap[type.name];
if (typeof mappedType == 'object') {
const importSource = mappedType.importSource;
let set = this.importedScalarTypes.get(importSource);
if (set === undefined) {
set = new Set<string>();
this.importedScalarTypes.set(importSource, set);
}
set.add(mappedType.typeName);
};
}
}
Example #8
Source File: GraphqlTypeInterpreter.ts From aloxide with Apache License 2.0 | 6 votes |
interpret(input: FieldTypeEnum): GraphQLScalarType {
let type: GraphQLScalarType;
switch (input) {
case FieldTypeEnum.uint16_t:
case FieldTypeEnum.uint32_t:
case FieldTypeEnum.uint64_t:
type = GraphQLInt;
break;
case FieldTypeEnum.number:
case FieldTypeEnum.double:
type = GraphQLFloat;
break;
case FieldTypeEnum.bool:
type = GraphQLBoolean;
break;
case FieldTypeEnum.account:
case FieldTypeEnum.string:
type = GraphQLString;
break;
default:
throw new Error(`unknow type ${type}`);
}
return type;
}
Example #9
Source File: GraphqlTypeInterpreter.ts From aloxide with Apache License 2.0 | 6 votes |
export class GraphqlTypeInterpreter implements Interpreter<FieldTypeEnum, GraphQLScalarType> {
interpret(input: FieldTypeEnum): GraphQLScalarType {
let type: GraphQLScalarType;
switch (input) {
case FieldTypeEnum.uint16_t:
case FieldTypeEnum.uint32_t:
case FieldTypeEnum.uint64_t:
type = GraphQLInt;
break;
case FieldTypeEnum.number:
case FieldTypeEnum.double:
type = GraphQLFloat;
break;
case FieldTypeEnum.bool:
type = GraphQLBoolean;
break;
case FieldTypeEnum.account:
case FieldTypeEnum.string:
type = GraphQLString;
break;
default:
throw new Error(`unknow type ${type}`);
}
return type;
}
}
Example #10
Source File: buildMutationInputType.ts From payload with MIT License | 6 votes |
getCollectionIDType = (config: SanitizedCollectionConfig): GraphQLScalarType => {
const idField = config.fields.find((field) => fieldAffectsData(field) && field.name === 'id');
if (!idField) return GraphQLString;
switch (idField.type) {
case 'number':
return GraphQLInt;
default:
return GraphQLString;
}
}
Example #11
Source File: renderResponseTypes.ts From genql with MIT License | 6 votes |
renderResponseTypes = (
schema: GraphQLSchema,
ctx: RenderContext,
) => {
let typeMap = schema.getTypeMap()
if (ctx.config?.sortProperties) {
typeMap = sortKeys(typeMap)
}
ctx.addCodeBlock(
renderScalarTypes(
ctx,
Object.values(typeMap).filter((type): type is GraphQLScalarType =>
isScalarType(type),
),
),
)
for (const name in typeMap) {
if (excludedTypes.includes(name)) continue
const type = typeMap[name]
if (isEnumType(type)) enumType(type, ctx)
if (isUnionType(type)) unionType(type, ctx)
if (isObjectType(type)) objectType(type, ctx)
if (isInterfaceType(type)) interfaceType(type, ctx)
}
const aliases = [
{ type: schema.getQueryType(), name: 'Query' },
{ type: schema.getMutationType(), name: 'Mutation' },
{ type: schema.getSubscriptionType(), name: 'Subscription' },
]
.map(renderAlias)
.filter(Boolean)
.join('\n')
ctx.addCodeBlock(aliases)
}
Example #12
Source File: scalarType.ts From genql with MIT License | 6 votes |
export function renderScalarTypes(
ctx: RenderContext,
types: GraphQLScalarType[],
) {
let content = ''
types.forEach((type) => {
content += ` ${type.name}: ${getTypeMappedAlias(type, ctx)},\n`
})
return `export type Scalars = {\n${content}}`
}
Example #13
Source File: BigInt.ts From squid with GNU General Public License v3.0 | 6 votes |
BigIntScalar = new GraphQLScalarType({
name: 'BigInt',
description: 'Big number integer',
serialize(value: number | string | bigint) {
return ''+value
},
parseValue(value: string) {
if (!isBigInt(value)) throw invalidFormat('BigInt', value)
return BigInt(value)
},
parseLiteral(ast) {
switch(ast.kind) {
case "StringValue":
if (isBigInt(ast.value)) {
return BigInt(ast.value)
} else {
throw invalidFormat('BigInt', ast.value)
}
case "IntValue":
return BigInt(ast.value)
default:
return null
}
}
})
Example #14
Source File: Bytes.ts From squid with GNU General Public License v3.0 | 6 votes |
BytesScalar = new GraphQLScalarType({
name: 'Bytes',
description: 'Binary data encoded as a hex string always prefixed with 0x',
serialize(value: string | Buffer) {
if (typeof value == 'string') {
if (!isHex(value)) throw invalidFormat('Bytes', value)
return value.toLowerCase()
} else {
return '0x' + value.toString('hex')
}
},
parseValue(value: string) {
return decodeHex(value)
},
parseLiteral(ast) {
switch(ast.kind) {
case "StringValue":
return decodeHex(ast.value)
default:
return null
}
}
})
Example #15
Source File: DateTime.ts From squid with GNU General Public License v3.0 | 6 votes |
DateTimeScalar = new GraphQLScalarType({
name: 'DateTime',
description:
'A date-time string in simplified extended ISO 8601 format (YYYY-MM-DDTHH:mm:ss.sssZ)',
serialize(value: Date | string) {
if (value instanceof Date) {
return value.toISOString()
} else {
if (!isIsoDateTimeString(value)) throw invalidFormat('DateTime', value)
return value
}
},
parseValue(value: string) {
return parseDateTime(value)
},
parseLiteral(ast) {
switch(ast.kind) {
case "StringValue":
return parseDateTime(ast.value)
default:
return null
}
}
})
Example #16
Source File: printers.ts From tql with MIT License | 6 votes |
printInputType = (type: GraphQLInputType): string => {
const isList = listType(type);
const base = inputType(type);
return (
(() => {
if (base instanceof GraphQLScalarType) {
return toPrimitive(base);
} else if (base instanceof GraphQLEnumType) {
return base.name;
} else if (base instanceof GraphQLInputObjectType) {
return "I" + base.name;
} else {
throw new Error("Unable to render inputType.");
}
})() + (isList ? "[]" : "")
);
}
Example #17
Source File: selectors.ts From tql with MIT License | 6 votes |
printArgument = (arg: GraphQLArgument): string => {
const type = inputType(arg.type);
const typename =
type instanceof GraphQLScalarType
? toPrimitive(type)
: type instanceof GraphQLEnumType
? type.toString()
: "I" + type.toString();
return `Argument<"${arg.name}", V['${arg.name}']>`;
}
Example #18
Source File: types.ts From tql with MIT License | 6 votes |
printField = (field: GraphQLField<any, any, any>): string => {
const { args } = field;
const isList = listType(field.type);
const isNonNull = field.type instanceof GraphQLNonNull;
const type = outputType(field.type);
const printVariables = () => {
return args.length > 0
? `(variables: { ${args.map(printVariable).join(", ")} })`
: "";
};
if (type instanceof GraphQLScalarType) {
return (
`${args.length > 0 ? "" : "readonly"} ${field.name}${printVariables()}: ${
isList ? `ReadonlyArray<${toPrimitive(type)}>` : `${toPrimitive(type)}`
}` + (isNonNull ? "" : " | null")
);
} else if (type instanceof GraphQLEnumType) {
return (
`${args.length > 0 ? "" : "readonly"} ${field.name}${printVariables()}: ${
isList ? `ReadonlyArray<${type.name}>` : `${type.name}`
}` + (isNonNull ? "" : " | null")
);
} else if (
type instanceof GraphQLInterfaceType ||
type instanceof GraphQLUnionType ||
type instanceof GraphQLObjectType
) {
return (
`${args.length > 0 ? "" : "readonly"} ${field.name}${printVariables()}: ${
isList ? `ReadonlyArray<I${type.name}>` : `I${type.name}`
}` + (isNonNull ? "" : " | null")
);
} else {
throw new Error("Unable to print field.");
}
}
Example #19
Source File: serializeToJSON.ts From amplify-codegen with Apache License 2.0 | 6 votes |
function serializeScalarType(type: GraphQLScalarType) {
const { name, description } = type;
return {
kind: 'ScalarType',
name,
description,
};
}
Example #20
Source File: primitive-value.scalar.ts From Cromwell with MIT License | 6 votes |
PrimitiveValueScalar = new GraphQLScalarType({
name: "PrimitiveValueScalar",
description: "Any primitive value",
parseValue(value: string) {
return parsePrimitiveValue(value);
},
serialize(value: string | number | boolean) {
return String(value);
},
parseLiteral(ast) {
if (ast.kind === Kind.STRING || ast.kind === Kind.INT || ast.kind === Kind.FLOAT || ast.kind === Kind.BOOLEAN) {
return parsePrimitiveValue(ast.value);
}
return null;
},
})
Example #21
Source File: helpers.ts From amplify-codegen with Apache License 2.0 | 6 votes |
describe('passthrough custom scalars', () => {
let getTypeAnnotation: Function;
beforeAll(() => {
getTypeAnnotation = createTypeAnnotationFromGraphQLTypeFunction({
passthroughCustomScalars: true,
});
});
test('Custom Scalar', () => {
const OddType = new GraphQLScalarType({
name: 'Odd',
serialize(value) {
return value % 2 === 1 ? value : null;
},
});
expect(getTypeAnnotation(OddType)).toMatchObject(t.nullableTypeAnnotation(t.anyTypeAnnotation()));
});
});
Example #22
Source File: objectid-scalar.ts From convoychat with GNU General Public License v3.0 | 6 votes |
ObjectIdScalar = new GraphQLScalarType({
name: "ObjectId",
description: "Mongo object id scalar type",
parseValue(value: string) {
return new ObjectId(value); // value from the client input variables
},
serialize(value: ObjectId) {
return value.toHexString(); // value sent to the client
},
parseLiteral(ast) {
if (ast.kind === Kind.STRING) {
return new ObjectId(ast.value); // value from the client query
}
return null;
},
})
Example #23
Source File: app.resolver.ts From svvs with MIT License | 6 votes |
resolverMap = {
Date: new GraphQLScalarType({
name: 'Date',
description: 'Date custom scalar type',
serialize(value: Date) {
return value.toISOString() // Value send to the client
},
parseValue(value: string) {
return new Date(value) // Value from the client
},
parseLiteral(ast) {
if (ast.kind === Kind.STRING) {
return new Date(ast.value) // ast value is always in string format
}
return null
},
}),
JSON: GraphQLJSON,
}
Example #24
Source File: getJSONSchemaStringFormatScalarMap.ts From graphql-mesh with MIT License | 6 votes |
export function getJSONSchemaStringFormatScalarMap(ajv: Ajv): Map<string, GraphQLScalarType> {
const map = new Map<string, GraphQLScalarType>();
for (const format of JSONSchemaStringFormats) {
const schema = {
type: 'string',
format,
};
const validate = ajv.compile(schema);
const coerceString = (value: string) => {
if (validate(value)) {
return value;
}
throw new Error(`Expected ${format} but got: ${value}`);
};
const scalar = new GraphQLScalarType({
name: pascalCase(format),
description: `Represents ${format} values`,
serialize: coerceString,
parseValue: coerceString,
parseLiteral: ast => {
if (ast.kind === Kind.STRING) {
return coerceString(ast.value);
}
throw new Error(`Expected string in ${format} format but got: ${(ast as any).value}`);
},
extensions: {
codegenScalarType: 'string',
},
});
map.set(format, scalar);
}
return map;
}
Example #25
Source File: helpers.ts From amplify-codegen with Apache License 2.0 | 6 votes |
// Types
typeNameFromGraphQLType(type: GraphQLType, unmodifiedTypeName?: string, isOptional?: boolean): string {
if (isNonNullType(type)) {
return this.typeNameFromGraphQLType(type.ofType, unmodifiedTypeName, false);
} else if (isOptional === undefined) {
isOptional = true;
}
let typeName;
if (isListType(type)) {
typeName = '[' + this.typeNameFromGraphQLType(type.ofType, unmodifiedTypeName) + ']';
} else if (type instanceof GraphQLScalarType) {
typeName = this.typeNameForScalarType(type);
} else {
typeName = unmodifiedTypeName || type.name;
}
return isOptional ? typeName + '?' : typeName;
}
Example #26
Source File: getComposerFromJSONSchema.ts From graphql-mesh with MIT License | 5 votes |
GraphQLVoid = new GraphQLScalarType({
name: 'Void',
description: 'Represents empty values',
serialize: () => '',
extensions: {
codegenScalarType: 'void',
},
})
Example #27
Source File: resolver.ts From one-platform with MIT License | 5 votes |
CommonResolver: IResolvers = {
DateTime: new GraphQLScalarType({
name: 'DateTime',
description: 'DateTime scalar for parsing and serializing DateTime objects',
serialize: (value: any) => {
return value.toISOString(); // Convert outgoing Date to ISO String for JSON
},
parseValue: (value: any) => {
if (isNaN(Date.parse(value))) {
throw new UserInputError('Invalid date format');
}
return new Date(value); // Convert incoming string | integer to Date
},
parseLiteral: (ast) => {
if (ast.kind === Kind.INT) {
return new Date(parseInt(ast.value, 10)); // Convert hard-coded AST string to integer and then to Date
} else if (ast.kind === Kind.STRING) {
return new Date(ast.value);
}
throw new UserInputError('Invalid date format'); // Invalid hard-coded value (not an integer)
},
}),
ObjectId: new GraphQLScalarType({
name: 'ObjectId',
description: 'MongoDB ObjectID',
serialize: (value: any) => {
return value.toString();
},
parseValue: (value: any) => {
if (ObjectId.isValid(value)) {
return new ObjectId(value);
}
throw new UserInputError('Invalid ObjectID');
},
parseLiteral: (ast) => {
if (ast.kind === Kind.STRING && ObjectId.isValid(ast.value)) {
return new ObjectId(ast.value);
}
throw new UserInputError('Invalid ObjectId');
},
}),
}
Example #28
Source File: selectors.ts From tql with MIT License | 5 votes |
printSignature = (field: GraphQLField<any, any, any>): string => {
const { name, args } = field;
const type = outputType(field.type);
const comments = [
field.description && `@description ${field.description}`,
field.deprecationReason && `@deprecated ${field.deprecationReason}`,
].filter(Boolean) as string[];
const jsDocComment =
comments.length > 0
? `
/**
${comments.map((comment) => "* " + comment).join("\n")}
*/
`
: "";
// @todo define Args type parameter as mapped type OR non-constant (i.e Array<Argument<...> | Argument<...>>)
if (type instanceof GraphQLScalarType || type instanceof GraphQLEnumType) {
return args.length > 0
? `${jsDocComment}\n readonly ${name}: <V extends { ${args
.map(printVariable)
.join(", ")} }>(variables: V) => Field<"${name}", [ ${args
.map(printArgument)
.join(", ")} ]>`
: `${jsDocComment}\n readonly ${name}: () => Field<"${name}">`;
} else {
// @todo restrict allowed Field types
return args.length > 0
? `
${jsDocComment}
readonly ${name}: <V extends { ${args
.map(printVariable)
.join(", ")} }, T extends ReadonlyArray<Selection>>(
variables: V,
select: (t: I${type.toString()}Selector) => T
) => Field<"${name}", [ ${args
.map(printArgument)
.join(", ")} ], SelectionSet<T>>,
`
: `
${jsDocComment}
readonly ${name}: <T extends ReadonlyArray<Selection>>(
select: (t: I${type.toString()}Selector) => T
) => Field<"${name}", never, SelectionSet<T>>,
`;
}
}
Example #29
Source File: selectors.ts From tql with MIT License | 5 votes |
printMethod = (field: GraphQLField<any, any, any>): string => {
const { name, args } = field;
const type = outputType(field.type);
const comments = [
field.description && `@description ${field.description}`,
field.deprecationReason && `@deprecated ${field.deprecationReason}`,
].filter(Boolean);
const jsDocComment =
comments.length > 0
? `
/**
${comments.map((comment) => "* " + comment).join("\n")}
*/
`
: "";
if (type instanceof GraphQLScalarType || type instanceof GraphQLEnumType) {
// @todo render arguments correctly
return args.length > 0
? jsDocComment.concat(
`${name}: (variables) => field("${name}", Object.entries(variables).map(([k, v]) => argument(k, v)) as any),`
)
: jsDocComment.concat(`${name}: () => field("${name}"),`);
} else {
const renderArgument = (arg: GraphQLArgument): string => {
return `argument("${arg.name}", variables.${arg.name})`;
};
// @todo restrict allowed Field types
return args.length > 0
? `
${jsDocComment}
${name}:(
variables,
select,
) => field("${name}", Object.entries(variables).map(([k, v]) => argument(k, v)) as any, selectionSet(select(${type.toString()}Selector))),
`
: `
${jsDocComment}
${name}: (
select,
) => field("${name}", undefined as never, selectionSet(select(${type.toString()}Selector))),
`;
}
}