Created
August 4, 2024 20:08
-
-
Save colinfwren/65ad08fb2999ab7af0a7c82c3aedab61 to your computer and use it in GitHub Desktop.
GraphQL context with Appwrite client
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {Account, Client, Databases, Models} from "node-appwrite"; | |
import {ListenOptions} from "node:net"; | |
import {ApolloServer} from "@apollo/server"; | |
import {startStandaloneServer} from "@apollo/server/standalone"; | |
async exampleFunction(databases: Databases, user: Models.User<Models.Preferences>) { | |
const doc = await databases.createDocument('databaseId', 'colId', user.$id) // do something with a database | |
} | |
const resolvers = { | |
Mutation: { | |
exampleMutation: async (_, reqBody, context) => await exampleFunction(context.databases, user) | |
} | |
} | |
async function createApolloServer(listenOption: ListenOptions = { port: 4000 }) { | |
const server = new ApolloServer<ServerContext>({ | |
typeDefs, | |
resolvers | |
}) | |
const { url } = await startStandaloneServer(server, { | |
context: async ({ req, res }) => { | |
// Get the JWT from the header | |
const token = req.headers.authorization.replace('Bearer', '') || '' | |
// Create Appwrite client using JWT to auth as user | |
const client = new Client() | |
.setEndpoint(APPWRITE_ENDPOINT) | |
.setProject(APPWRITE_PROJECT) | |
.setJWT(token) | |
const databases = new Databases(client) | |
const account = new Account(client) | |
const user = await account.get() | |
return { | |
client, | |
databases, | |
user | |
} | |
}, | |
listen: listenOptions | |
}) | |
return { server, url } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment