DEV Community 👩‍💻👨‍💻

Cover image for How to add a Graphql endpoint into a Sveltekit app
vibhanshu pandey
vibhanshu pandey

Posted on

How to add a Graphql endpoint into a Sveltekit app

Warning: The code provided in this post is not well tested for every environment, and may not provide all the features, use with caution.

Hello, In this post I will show you how you can add a graphql endpoint in a sveltekit app with apollo-server-lambda.

TLDR;

If you want to start quickly, here's the boilerplate Repo: https://github.com/vibhanshu909/sveltekit-with-graphql

Note: I'm using typescript here, if you don't use typescript, make the required changes.
This Project also uses tailwindcss, if you don't want to use tailwindcss, perform the following steps.

  • Delete postcss.config.cjs, tailwindcss.config.cjs & src/app.css files.
  • remove postcss: true option in preprocess function from svelte.config.js file.
  • remove import '../app.css'; statement from the script block in __layout.svelte file.

Follow the below steps.

Step 1: Install the required dependencies

npm i apollo-server-lambda graphql
Enter fullscreen mode Exit fullscreen mode

Step 2: create a file src/routes/graphql.ts with the following contents.

import type { EndpointOutput, RequestHandler } from '@sveltejs/kit';
import { ApolloServer, gql } from 'apollo-server-lambda';

const typeDefs = gql`
    type Query {
        hello: String
    }
    type Mutation {
        double(x: Int!): Int!
    }
`;

// Provide resolver functions for your schema fields
const resolvers = {
    Query: {
        hello: () => 'Hello world!'
    },
    Mutation: {
        double: (_, { x }) => x * 2
    }
};

const apolloServer = new ApolloServer({
    typeDefs,
    resolvers,
    playground: true,
    introspection: true,
    tracing: true
});

const graphqlHandler = apolloServer.createHandler();

// This is where the magic happens.
const handler: RequestHandler = async (args) => {
    return await new Promise<EndpointOutput>((resolve, reject) => {
        graphqlHandler(
            {
                httpMethod: args.method,
                headers: args.headers,
                path: args.path,
                body: args.rawBody as string
            } as any,
            {} as any,
            (err, result) => {
                if (err) {
                    reject(err);
                } else {
                    resolve({
                        status: result.statusCode,
                        body: result.body,
                        headers: result.headers as any
                    });
                }
            }
        ) as any;
    });
};

export const head = handler;
export const get = handler;
export const post = handler;

Enter fullscreen mode Exit fullscreen mode

Step 3: Test the endpoint.

npm run dev
Enter fullscreen mode Exit fullscreen mode

Goto http://localhost:3000/graphql, you should see the graphql playground.

And that's it. :)

Comment down below, if you have any questions.

Top comments (2)

Collapse
 
jdgamble555 profile image
Jonathan Gamble • Edited on

This does not work with SvelteKit.

I got mine to work with this:

const handler = async ({ request }) => {

  const r = await request.json();

  return {
    body: await server.executeOperation(r)
  };

}

export const head = handler;
export const get = handler;
export const post = handler;
Enter fullscreen mode Exit fullscreen mode
Collapse
 
vibhanshu909 profile image
vibhanshu pandey

Yes, Unfortunately this no longer works, there's been a number of updates in the sveltekit repo.

Thinking of Archiving this, until further updates.

Regex for lazy developers

regex for lazy devs

You know who you are. Sorry for the callout 😆