
Security News
Deno 2.2 Improves Dependency Management and Expands Node.js Compatibility
Deno 2.2 enhances Node.js compatibility, improves dependency management, adds OpenTelemetry support, and expands linting and task automation for developers.
graphql-jit
Advanced tools
The graphql-jit package is designed to optimize the execution of GraphQL queries by compiling them into JavaScript functions. This can significantly improve the performance of GraphQL servers by reducing the overhead associated with parsing and interpreting queries at runtime.
Query Compilation
This feature allows you to compile a GraphQL query into a JavaScript function, which can then be executed. This reduces the overhead of parsing and interpreting the query at runtime, leading to improved performance.
const { compileQuery } = require('graphql-jit');
const { parse, validate, execute, specifiedRules } = require('graphql');
const schema = /* your GraphQL schema */;
const document = parse(/* your GraphQL query */);
const validationErrors = validate(schema, document, specifiedRules);
if (validationErrors.length > 0) {
throw new Error('Validation failed');
}
const compiledQuery = compileQuery(schema, document, 'QueryName');
const result = compiledQuery.query({}, {}, {});
console.log(result);
Custom Execution Context
This feature allows you to pass a custom execution context to the compiled query function. This can be useful for injecting dependencies or other contextual information needed during query execution.
const { compileQuery } = require('graphql-jit');
const { parse, validate, specifiedRules } = require('graphql');
const schema = /* your GraphQL schema */;
const document = parse(/* your GraphQL query */);
const validationErrors = validate(schema, document, specifiedRules);
if (validationErrors.length > 0) {
throw new Error('Validation failed');
}
const compiledQuery = compileQuery(schema, document, 'QueryName');
const customContext = { /* your custom context */ };
const result = compiledQuery.query({}, {}, customContext);
console.log(result);
The 'graphql' package is the reference implementation of GraphQL for JavaScript. It provides the core functionality for defining schemas, parsing queries, and executing them. While it is highly flexible and widely used, it does not offer the same level of performance optimization as graphql-jit, which focuses on compiling queries to improve execution speed.
Apollo Server is a popular GraphQL server implementation that integrates well with various data sources and provides features like caching, subscriptions, and more. While it offers a rich set of features for building GraphQL APIs, it does not focus on query compilation for performance optimization like graphql-jit.
graphql-tools is a set of utilities for building and manipulating GraphQL schemas in JavaScript. It provides tools for schema stitching, mocking, and more. While it is useful for schema development and testing, it does not offer the query compilation and execution performance optimizations provided by graphql-jit.
GraphQL-JS is a very well written runtime implementation of the latest GraphQL spec. However, by compiling to JS, V8 is able to create optimized code while yields much better performance.
The goal is to support the June 2018 version of the GraphQL spec. At this moment, the only missing feature is support for the @skip and @include directives.
In order to achieve better performance, the compiler introduces some limitations. The main one is that all computed properties must have a resolver and only these can return a Promise.
yarn add graphql-jit
This is an example of a handler that could be used with express
or micro
.
const httpErrors = require('http-errors');
const {getGraphQLParams} = require("express-graphql");
const graphql = require('graphql');
const LRU = require("lru-cache");
const {compileQuery} = require("graphql-jit");
module.exports = function setupHandler(schema, disableLeafSerialization) {
const cache = LRU({max: 100});
return function graphqlMiddleware(request, response) {
// Promises are used as a mechanism for capturing any thrown errors during
// the asynchronous process below.
// Parse the Request to get GraphQL request parameters.
return getGraphQLParams(request).then(function (graphQLParams) {
// Collect information from the options data object.
let context = request;
let rootValue = undefined;
let validationRules = graphql.specifiedRules;
// GraphQL HTTP only supports GET and POST methods.
if (request.method !== 'GET' && request.method !== 'POST') {
response.setHeader('Allow', 'GET, POST');
throw httpErrors(405, 'GraphQL only supports GET and POST requests.');
}
// Get GraphQL params from the request and POST body data.
const query = graphQLParams.query;
const variables = graphQLParams.variables;
const operationName = graphQLParams.operationName;
// If there is no query, but GraphiQL will be displayed, do not produce
// a result, otherwise return a 400: Bad Request.
if (!query) {
throw httpErrors(400, 'Must provide query string.');
}
let cached = cache.get(query + operationName);
if (!cached) {
// GraphQL source.
let source = new graphql.Source(query, 'GraphQL request');
let documentAST;
// Parse source to AST, reporting any syntax error.
try {
documentAST = graphql.parse(source);
} catch (syntaxError) {
// Return 400: Bad Request if any syntax errors errors exist.
response.statusCode = 400;
return {errors: [syntaxError]};
}
// Validate AST, reporting any errors.
let validationErrors = graphql.validate(schema, documentAST, validationRules);
if (validationErrors.length > 0) {
// Return 400: Bad Request if any validation errors exist.
response.statusCode = 400;
return {errors: validationErrors};
}
// Only query operations are allowed on GET requests.
if (request.method === 'GET') {
// Determine if this GET request will perform a non-query.
let operationAST = graphql.getOperationAST(documentAST, operationName);
if (operationAST && operationAST.operation !== 'query') {
// Otherwise, report a 405: Method Not Allowed error.
response.setHeader('Allow', 'POST');
throw httpErrors(405, 'Can only perform a ' + operationAST.operation + ' operation ' + 'from a POST request.');
}
}
cached = compileQuery(schema, documentAST, operationName, {disableLeafSerialization});
cache.set(query + operationName, cached)
}
// Perform the execution, reporting any errors creating the context.
try {
return cached.query(rootValue, context, variables);
} catch (contextError) {
// Return 400: Bad Request if any execution context errors exist.
response.statusCode = 400;
return {errors: [contextError]};
}
}).catch(function (error) {
// If an error was caught, report the httpError status, or 500.
response.statusCode = error.status || 500;
return {errors: [error]};
}).then(function (result) {
// If no data was included in the result, that indicates a runtime query
// error, indicate as such with a generic status code.
// Note: Information about the error itself will still be contained in
// the resulting JSON payload.
// http://facebook.github.io/graphql/#sec-Data
if (response.statusCode === 200 && result && !result.data) {
response.statusCode = 500;
}
// Format any encountered errors.
if (result && result.errors) {
result.errors = result.errors.map(graphql.formatError);
}
// At this point, result is guaranteed to exist, as the only scenario
// where it will not is when showGraphiQL is true.
if (!result) {
throw httpErrors(500, 'Internal Error');
}
return result
});
};
}
Compiles the document
AST, using an optional operationName and compiler options.
schema
{GraphQLSchema} - graphql-js
schema object
document
{DocumentNode} - document query AST ,can be obtained by parse
from graphql-js
operationName
{string} - optional operation name in case the document contains multiple queries/operations.
compilerOptions
{Object} - Configurable options on the agent pool
disableLeafSerialization
{boolean, default: false} - disables leaf node serializers. The serializers validate the content of the field
so this option should only be set to true if there are strong assurances that the values are valid.customJSONSerializer
{boolean, default: false} - Whether to produce also a JSON serializer function using fast-json-stringify
,
otherwise the stringify function is just JSON.stringify
the compiled function that can be called with a root value, a context and the required variables.
the compiled function for producing a JSON string. It will be JSON.stringify
unless compilerOptions.customJSONSerializer
is true.
The value argument should the return of the compiled GraphQL function.
MIT
FAQs
GraphQL JIT Compiler to JS
The npm package graphql-jit receives a total of 83,555 weekly downloads. As such, graphql-jit popularity was classified as popular.
We found that graphql-jit demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 3 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Deno 2.2 enhances Node.js compatibility, improves dependency management, adds OpenTelemetry support, and expands linting and task automation for developers.
Security News
React's CRA deprecation announcement sparked community criticism over framework recommendations, leading to quick updates acknowledging build tools like Vite as valid alternatives.
Security News
Ransomware payment rates hit an all-time low in 2024 as law enforcement crackdowns, stronger defenses, and shifting policies make attacks riskier and less profitable.