npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@dashdot/graphql-server

v1.0.0

Published

A high performance graphql handler using the power of JIT.

Downloads

534

Readme

Dashdot Graphql Server

build codecov

A simple high performance graphql handler using the power of JIT.

Usage

Inside your Node project directory, run the following:

npm i --save @dashdot/graphql-server

Or with Yarn:

yarn add @dashdot/graphql-server

Example

import { createServer } from 'http'
import {
    GraphqlQueryStore,
    createGraphqlRequestHandler
} from '@dashdot/graphql-server'
import schema from './schema'

const { PORT, HOST } = process.env

const store = new GraphqlQueryStore(schema)

const server = createServer(
    createGraphqlRequestHandler(store)
)

server.listen(PORT, HOST, () => {
    console.log(`Server started and listening on http://${HOST}:${PORT}`)
})

API

Dashdot Graphql Server is a simple graphql request processor designed to be framework agnostic. You can use it either with the default Node http server or implement it in your own framework. The library exposes 2 main functions:

Where createGraphqlRequestHandler is just an implementation of processGraphqlRequest using the native Node http package.

What do these functions do? As little as possible. We designed this library to reduce the overhead provided by other libraries. The library processes and validates a Graphql request and passes it to your schema to be interpreted. In sequence here are the steps that are taken:

  • Do we have a valid request (are we uploading something)?
  • Validate (and compile) the query
  • Create the request context
  • Pass query and context to your schema
  • Return the result

You schema is not passed directly to the request handler, instead we pass it to a GraphqlQueryStore. The query store wil use the power of JIT (just-in-time compilation) to improve the query performance. You can read more about this here.

processGraphqlRequest

export default function processGraphqlRequest(
    req: IncomingMessage,
    options: ProcessGraphqlRequestOptions
): Promise<GraphqlResponse>;

ProcessGraphqlRequestOptions

type ProcessGraphqlRequestOptions = {
    store: GraphqlQueryStore
    context: any
    processFileUploads?: (req: IncomingMessage) => Promise<any>
    readRequestBody: (req: IncomingMessage) => Promise<any>
}

GraphqlResponse

type GraphqlResponse = {
    status: number
    text?: string
    body?: any
}

Security

While we try to minimize the overhead of this library it offers basic protection against query complexity attacks using the graphql-query-complexity package. You can customize this basic config by setting the defaultComplexity and maximumComplexity complexity options for the GraphqlQueryStore. You can also extend the validation rules by providing your own custom rules as validationRules option.

type QueryComplexityOptions = {
    maximumComplexity?: number
    defaultComplexity?: number
}

type GraphqlQueryStoreOptions = {
    validationRules?: [ValidationRule]
    queryComplexity?: QueryComplexityOptions
} 

class GraphqlQueryStore {
    constructor(
        schema: GraphQLSchema,
        options?: GraphqlQueryStoreOptions
    ) {}
}

How do I implement this in framework X

By using the processGraphqlRequest function. This function takes a request (like) object and some options to process the graphql request Below you can find an example of an implementation in Next.js and Express.

Example Next.js

// /api/graphql/route.js

import type { NextRequest } from 'next/server'
import { GraphqlQueryStore, processGraphqlRequest } from '@dashdot/graphql-server'
import { createSchema } from './createSchema'
import { createRequestContext } from './requestContext'

const schema = createSchema()
const store = new GraphqlQueryStore(schema)

export async function POST(req: NextRequest) {
    try {
        const { status, text, body } = await processGraphqlRequest(req, {
            store,
            context: createRequestContext(req),
            readRequestBody: () => req.json(),
        })
        if (text) {
            return new Response(text, { status })
        }
        if (body) {
            return Response.json(body, { status })
        }
    } catch (e) {
        return new Response(e.message, { status: 500 })
    }
}

Example Express

// graphql.js

import {
    GraphqlQueryStore,
    processGraphqlRequest,
} from '@dashdot/graphql-server'
import { createSchema } from './createSchema'
import { createRequestContext } from './requestContext'
import app from './app'

const schema = createSchema()
const store = new GraphqlQueryStore(schema)

app.post('/api/graphql', async (req, res) => {
    try {
        const { status, text, body } = await processGraphqlRequest({ 
            store,
            context: createRequestContext(req),
            readRequestBody: async () => {
                // Assuming you're using bodyParser or similar middleware
                return req.body
            },
        })
        if (text) {
            res.status(status).send(text)
        } else if (body) {
            res.status(status).json(body)
        }
    } catch (e) {
        res.status(500).send(e.message)
    }
})