Build type-safe GraphQL APIs with TypeScript, Apollo Server, and automated type generation.
# TypeScript GraphQL Server
Build type-safe GraphQL APIs with TypeScript using Google Antigravity IDE. This comprehensive guide covers schema design, resolvers, authentication, and performance optimization.
## Why TypeScript GraphQL?
GraphQL with TypeScript provides end-to-end type safety. Google Antigravity IDE's Gemini 3 engine generates resolvers and validates schema consistency automatically.
## Schema Definition
```typescript
// src/schema/typeDefs.ts
import { gql } from "graphql-tag";
export const typeDefs = gql`
scalar DateTime
scalar JSON
type Query {
user(id: ID!): User
users(filter: UserFilter, pagination: PaginationInput): UserConnection!
me: User
}
type Mutation {
createUser(input: CreateUserInput!): User!
updateUser(id: ID!, input: UpdateUserInput!): User!
deleteUser(id: ID!): Boolean!
login(email: String!, password: String!): AuthPayload!
}
type Subscription {
userCreated: User!
userUpdated(id: ID!): User!
}
type User {
id: ID!
email: String!
name: String!
role: UserRole!
posts(first: Int, after: String): PostConnection!
createdAt: DateTime!
updatedAt: DateTime!
}
type Post {
id: ID!
title: String!
content: String!
author: User!
publishedAt: DateTime
}
type AuthPayload {
token: String!
user: User!
}
type UserConnection {
edges: [UserEdge!]!
pageInfo: PageInfo!
totalCount: Int!
}
type UserEdge {
node: User!
cursor: String!
}
type PageInfo {
hasNextPage: Boolean!
hasPreviousPage: Boolean!
startCursor: String
endCursor: String
}
input CreateUserInput {
email: String!
password: String!
name: String!
role: UserRole
}
input UpdateUserInput {
name: String
role: UserRole
}
input UserFilter {
email: String
name: String
role: UserRole
}
input PaginationInput {
first: Int
after: String
last: Int
before: String
}
enum UserRole {
ADMIN
USER
GUEST
}
`;
```
## Resolvers with DataLoader
```typescript
// src/resolvers/userResolvers.ts
import { Resolvers, UserResolvers } from "../generated/graphql";
import { Context } from "../context";
import DataLoader from "dataloader";
// Create DataLoader to batch user queries
function createUserLoader(db: Database) {
return new DataLoader<string, User>(async (ids) => {
const users = await db.user.findMany({
where: { id: { in: [...ids] } },
});
const userMap = new Map(users.map((u) => [u.id, u]));
return ids.map((id) => userMap.get(id) || null);
});
}
export const userResolvers: Resolvers<Context> = {
Query: {
user: async (_, { id }, { dataSources }) => {
return dataSources.userLoader.load(id);
},
users: async (_, { filter, pagination }, { db }) => {
const { first = 20, after } = pagination || {};
const users = await db.user.findMany({
where: filter ? buildFilter(filter) : undefined,
take: first + 1,
cursor: after ? { id: after } : undefined,
orderBy: { createdAt: "desc" },
});
const hasNextPage = users.length > first;
const edges = users.slice(0, first).map((user) => ({
node: user,
cursor: user.id,
}));
return {
edges,
pageInfo: {
hasNextPage,
hasPreviousPage: !!after,
startCursor: edges[0]?.cursor,
endCursor: edges[edges.length - 1]?.cursor,
},
totalCount: await db.user.count(),
};
},
me: async (_, __, { user }) => {
if (!user) throw new AuthenticationError("Not authenticated");
return user;
},
},
Mutation: {
createUser: async (_, { input }, { db, pubsub }) => {
const user = await db.user.create({
data: {
...input,
password: await hashPassword(input.password),
},
});
pubsub.publish("USER_CREATED", { userCreated: user });
return user;
},
},
Subscription: {
userCreated: {
subscribe: (_, __, { pubsub }) =>
pubsub.asyncIterator(["USER_CREATED"]),
},
},
User: {
posts: async (parent, { first, after }, { db }) => {
// Resolve posts for user
return db.post.findMany({
where: { authorId: parent.id },
take: first || 10,
});
},
},
};
```
## Context and Authentication
```typescript
// src/context.ts
import { PrismaClient } from "@prisma/client";
import { PubSub } from "graphql-subscriptions";
import { verifyToken } from "./auth";
export interface Context {
db: PrismaClient;
pubsub: PubSub;
user: User | null;
dataSources: {
userLoader: DataLoader<string, User>;
};
}
export async function createContext({ req }): Promise<Context> {
const token = req.headers.authorization?.replace("Bearer ", "");
const user = token ? await verifyToken(token) : null;
return {
db: prisma,
pubsub: new PubSub(),
user,
dataSources: {
userLoader: createUserLoader(prisma),
},
};
}
```
## Best Practices
- Use DataLoader to prevent N+1 queries
- Implement cursor-based pagination
- Apply field-level authorization
- Use code generation for type safety
- Cache frequently accessed data
- Monitor query complexity and depth
Google Antigravity IDE provides GraphQL schema validation and automatically generates TypeScript types from your schema.This TypeScript prompt is ideal for developers working on:
By using this prompt, you can save hours of manual coding and ensure best practices are followed from the start. It's particularly valuable for teams looking to maintain consistency across their typescript implementations.
Yes! All prompts on Antigravity AI Directory are free to use for both personal and commercial projects. No attribution required, though it's always appreciated.
This prompt works excellently with Claude, ChatGPT, Cursor, GitHub Copilot, and other modern AI coding assistants. For best results, use models with large context windows.
You can modify the prompt by adding specific requirements, constraints, or preferences. For TypeScript projects, consider mentioning your framework version, coding style, and any specific libraries you're using.