本文整理汇总了TypeScript中graphql.parse函数的典型用法代码示例。如果您正苦于以下问题:TypeScript parse函数的具体用法?TypeScript parse怎么用?TypeScript parse使用的例子?那么, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了parse函数的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1: it
it('should remove empty selection sets on wrapped objects (non-nullable/lists)', async () => {
const query = parse(`
query bookingQuery($id: ID!) {
bookingById(id: $id) {
id
propertyId
customer {
favoriteFood
}
}
}
`);
const filteredQuery = filter.transformRequest({
document: query,
variables: {
id: 'b1'
}
});
const expected = parse(`
query bookingQuery($id: ID!) {
bookingById(id: $id) {
id
propertyId
}
}
`);
expect(print(filteredQuery.document)).to.equal(print(expected));
});
示例2: it
it("the documentStore calculates the DocumentNode's length by its JSON.stringify'd representation", async () => {
expect.assertions(14);
const {
plugins,
events: { parsingDidStart, validationDidStart },
} = createLifecyclePluginMocks();
const queryLarge = forgeLargerTestQuery(3, 'large');
const querySmall1 = forgeLargerTestQuery(1, 'small1');
const querySmall2 = forgeLargerTestQuery(1, 'small2');
// We're going to create a smaller-than-default cache which will be the
// size of the two smaller queries. All three of these queries will never
// fit into this cache, so we'll roll through them all.
const maxSize =
approximateObjectSize(parse(querySmall1)) +
approximateObjectSize(parse(querySmall2));
const documentStore = new InMemoryLRUCache<DocumentNode>({
maxSize,
sizeCalculator: approximateObjectSize,
});
await runRequest({ plugins, documentStore, queryString: querySmall1 });
expect(parsingDidStart.mock.calls.length).toBe(1);
expect(validationDidStart.mock.calls.length).toBe(1);
await runRequest({ plugins, documentStore, queryString: querySmall2 });
expect(parsingDidStart.mock.calls.length).toBe(2);
expect(validationDidStart.mock.calls.length).toBe(2);
// This query should be large enough to evict both of the previous
// from the LRU cache since it's larger than the TOTAL limit of the cache
// (which is capped at the length of small1 + small2) â though this will
// still fit (barely).
await runRequest({ plugins, documentStore, queryString: queryLarge });
expect(parsingDidStart.mock.calls.length).toBe(3);
expect(validationDidStart.mock.calls.length).toBe(3);
// Make sure the large query is still cached (No incr. to parse/validate.)
await runRequest({ plugins, documentStore, queryString: queryLarge });
expect(parsingDidStart.mock.calls.length).toBe(3);
expect(validationDidStart.mock.calls.length).toBe(3);
// This small (and the other) should both trigger parse/validate since
// the cache had to have evicted them both after accommodating the larger.
await runRequest({ plugins, documentStore, queryString: querySmall1 });
expect(parsingDidStart.mock.calls.length).toBe(4);
expect(validationDidStart.mock.calls.length).toBe(4);
await runRequest({ plugins, documentStore, queryString: querySmall2 });
expect(parsingDidStart.mock.calls.length).toBe(5);
expect(validationDidStart.mock.calls.length).toBe(5);
// Finally, make sure that the large query is gone (it should be, after
// the last two have taken its spot again.)
await runRequest({ plugins, documentStore, queryString: queryLarge });
expect(parsingDidStart.mock.calls.length).toBe(6);
expect(validationDidStart.mock.calls.length).toBe(6);
});
示例3: parseFragmentToInlineFragment
function parseFragmentToInlineFragment(
definitions: string,
): InlineFragmentNode {
if (definitions.trim().startsWith('fragment')) {
const document = parse(definitions);
for (const definition of document.definitions) {
if (definition.kind === Kind.FRAGMENT_DEFINITION) {
return {
kind: Kind.INLINE_FRAGMENT,
typeCondition: definition.typeCondition,
selectionSet: definition.selectionSet,
};
}
}
}
const query = parse(`{${definitions}}`)
.definitions[0] as OperationDefinitionNode;
for (const selection of query.selectionSet.selections) {
if (selection.kind === Kind.INLINE_FRAGMENT) {
return selection;
}
}
throw new Error('Could not parse fragment');
}
示例4: fetchAndPrintSchema
export async function fetchAndPrintSchema(
client: Client,
serviceName: string,
stageName: string,
token?: string,
): Promise<string> {
const introspection = await client.introspect(serviceName, stageName, token)
const schema = buildClientSchema(introspection)
const sdl = printSchema(schema)
const document = parse(sdl)
const groupedDefinitions = groupBy(document.definitions, classifyDefinition)
let sortedDefinitions: DefinitionNode[] = []
typesOrder.map(type => {
const definitions = groupedDefinitions[type]
sortedDefinitions = sortedDefinitions.concat(definitions)
})
let newSdl = print({
kind: Kind.DOCUMENT,
definitions: sortedDefinitions,
})
const newDocument = parse(newSdl)
// add comments to document
let countOffset = 0
let charOffset = 0
typesOrder.forEach((type, index) => {
if (!groupedDefinitions[type]) {
return
}
const definitionCount = groupedDefinitions[type].length
const definitions = newDocument.definitions.slice(
countOffset,
definitionCount,
)
const start = definitions[0].loc!.start
const comment = `\
${index > 0 ? '\n' : ''}#
# ${descriptions[type]}
#\n\n`
newSdl =
newSdl.slice(0, start + charOffset) +
comment +
newSdl.slice(start + charOffset)
charOffset += comment.length
countOffset += definitionCount
})
const header = `# THIS FILE HAS BEEN AUTO-GENERATED BY "PRISMA DEPLOY"
# DO NOT EDIT THIS FILE DIRECTLY\n\n`
return header + newSdl
}
示例5: blackBoxTest
export default function blackBoxTest(name: string) {
const generators = new Generators()
const modelPath = path.join(__dirname, `cases/${name}/model.graphql`)
const prismaPath = path.join(__dirname, `cases/${name}/prisma.graphql`)
expect(fs.existsSync(modelPath))
expect(fs.existsSync(prismaPath))
const model = fs.readFileSync(modelPath, { encoding: 'UTF-8' })
const prisma = fs.readFileSync(prismaPath, { encoding: 'UTF-8' })
const types = DatamodelParser.parseFromSchemaString(model)
const ourSchema = generators.schema.generate(types, {})
const ourPrintedSchema = printSchema(ourSchema)
// Write a copy of the generated schema to the FS, for debugging
fs.writeFileSync(
path.join(__dirname, `cases/${name}/generated.graphql`),
ourPrintedSchema,
{ encoding: 'UTF-8' },
)
// Check if our schema equals the prisma schema.
const prismaSchema = buildSchema(prisma)
AstTools.assertTypesEqual(prismaSchema, ourSchema)
// Check if we can parse the schema we build (e.g. it's syntactically valid).
parse(ourPrintedSchema)
}
示例6: put
public put(operationDefinition: string): void {
const ast = parse(operationDefinition);
function isOperationDefinition(definition): definition is OperationDefinition {
return definition.kind === OPERATION_DEFINITION;
}
if (ast.definitions.length > 1) {
throw new Error('operationDefinition must contain only one definition');
}
const definition = ast.definitions[0];
if (isOperationDefinition(definition)) {
const validationErrors = validate(this.schema, ast);
if (validationErrors.length > 0) {
const messages = validationErrors.map((e) => e.message);
const e = new Error(`Validation Errors:\n${messages.join('\n')}`);
e['originalErrors'] = validationErrors;
throw e;
}
this.storedOperations.set(definition.name.value, ast);
} else {
throw new Error(`operationDefinition must contain an OperationDefinition: ${operationDefinition}`);
}
}
示例7: function
export const jsSchemaLoader: SchemaLoader = async function (options: TJsSchemaLoaderOptions) {
const schemaPath = resolve(options.schemaFile);
let schemaModule = require(schemaPath);
let schema: string;
// check if exist default in module
if (typeof schemaModule === 'object') {
schemaModule = schemaModule.default
}
// check for array of definition
if (Array.isArray(schemaModule)){
schema = schemaModule.join('');
// check for array array wrapped in a function
} else if (typeof schemaModule === 'function') {
schema = schemaModule().join('');
} else {
throw new Error(`Unexpected schema definition on "${schemaModule}", must be an array or function`)
}
const introspection = await execute(
buildSchema(schema),
parse(introspectionQuery)
) as Introspection;
return introspection.data.__schema;
};
示例8: put
public put(operation: string | DocumentNode): void {
function isOperationDefinition(definition): definition is OperationDefinitionNode {
return definition.kind === Kind.OPERATION_DEFINITION;
}
function isString(definition): definition is string {
return typeof definition === 'string';
}
const ast = isString(operation) ? parse(operation as string) : operation as DocumentNode;
const definitions = ast.definitions.filter(isOperationDefinition) as OperationDefinitionNode[];
if (definitions.length === 0) {
throw new Error('OperationDefinitionNode must contain at least one definition');
}
if (definitions.length > 1) {
throw new Error('OperationDefinitionNode must contain only one definition');
}
const validationErrors = validate(this.schema, ast);
if (validationErrors.length > 0) {
const messages = validationErrors.map((e) => e.message);
const err = new Error(`Validation Errors:\n${messages.join('\n')}`);
err['originalErrors'] = validationErrors;
throw err;
}
this.storedOperations.set(definitions[0].name.value, ast);
}