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 inpreprocess
function fromsvelte.config.js
file.- remove
import '../app.css';
statement from thescript
block in__layout.svelte
file.
Follow the below steps.
Step 1: Install the required dependencies
npm i apollo-server-lambda graphql
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;
Step 3: Test the endpoint.
npm run dev
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)
This does not work with SvelteKit.
I got mine to work with this:
Yes, Unfortunately this no longer works, there's been a number of updates in the sveltekit repo.
Thinking of Archiving this, until further updates.