To create a simple API server using Apollo GraphQL, TypeScript, Prisma ORM with PostgreSQL to fetch a list of books, you'll need to set up several components. Here's a step-by-step guide, assuming that you already have PostgreSQL and Node.js installed.
1. Initialize the Project
First, create a new directory for your project, navigate into it, and initialize a new Node.js project:
mkdir books-api
cd books-api
npm init -y
2. Install Dependencies
Install the necessary dependencies for Apollo Server, GraphQL, Prisma, and TypeScript:
npm install apollo-server graphql
npm install @prisma/client
npm install typescript ts-node @types/node @types/graphql --save-dev
3. Set Up TypeScript
Create a tsconfig.json file for TypeScript configuration:
{
"compilerOptions": {
"target": "ES2017",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"outDir": "dist"
},
"include": ["src"]
}
4. Set Up Prisma
Install the Prisma CLI as a development dependency:
npm install prisma --save-dev
Initialize Prisma and create your database schema:
npx prisma init
Edit the .env file to point to your PostgreSQL database:
DATABASE_URL="postgresql://user:password@localhost:5432/mydb"
Define your data model in prisma/schema.prisma:
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
generator client {
provider = "prisma-client-js"
}
model Book {
id Int @id @default(autoincrement())
title String
author String
}
Generate the Prisma Client:
npx prisma generate
Apply the database migrations:
npx prisma migrate dev --name init
5. Create the Apollo Server
Create a src directory and inside create an index.ts file:
import { ApolloServer, gql } from 'apollo-server';
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
// GraphQL schema
const typeDefs = gql`
type Book {
id: Int
title: String
author: String
}
type Query {
books: [Book]
}
`;
// Resolvers
const resolvers = {
Query: {
books: async () => {
return await prisma.book.findMany();
},
},
};
// Apollo Server setup
const server = new ApolloServer({
typeDefs,
resolvers,
});
// Start the server
server.listen().then(({ url }) => {
console.log(`🚀 Server ready at ${url}`);
});
6. Run the Server
Make sure your PostgreSQL server is running and then start your server using:
npx ts-node src/index.ts
7. Testing the Server
Once the server is running, you can test your GraphQL API by navigating to http://localhost:4000 in your browser or using a tool like Postman or GraphQL Playground, which will be available automatically with Apollo Server. Use the following query to fetch the list of books:
query {
books {
id
title
author
}
}
Conclusion
This setup provides a basic GraphQL API server built with Apollo Server, TypeScript, Prisma ORM, and PostgreSQL. You can expand this with additional queries, mutations, and more complex relationships to suit your needs.