what is the flow when programming with prisma orm, graphql nexus and apollo? what are the steps? let say i want to add users table to store user, and sync them from jwt. i am creating the api.
Assistant
User
why i need to write model/schema twice, once for prisma and once for nexus? is there single source of truth?
Assistant
User
for let say i adding posts table, how to add seeds when table is created? for dev env needs?
Assistant
User
can i somehow generate random values, if i need for example 10k records?
Assistant
Creating a GraphQL API using Prisma ORM, GraphQL Nexus, and Apollo involves several steps. Let's walk through the process of adding a User table to manage users and sync them from JWT. Here's a general flow you can follow:
To sync users from JWT, you'll typically extract user information from the JWT in the context creation. Example:
typescript
const server = new ApolloServer({
schema,
context: ({ req }) => {
const token = req.headers.authorization || ''
const user = getUserFromToken(token) // Implement this function to decode your JWT
return { prisma, user }
},
})
7. Implementing getUserFromToken
You'll need to implement this function to parse the JWT, verify it, and extract user information:
typescript
import jwt from 'jsonwebtoken'
function getUserFromToken(token) {
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET)
return decoded.user
} catch (e) {
throw new Error('Not authenticated')
}
}
8. Test Your API
With the server running, use a tool like GraphQL Playground (which Apollo Server offers by default in dev mode) to test querying and mutating your data.
Final Thoughts
This example provides a high-level overview but leaves out many important aspects, such as error handling, input validation, authentication, authorization, and a robust project structure. Consider these when developing a production-ready application.
The separation of schema definitions between Prisma and Nexus is a common point of confusion and a topic of active development and discussion in the Node.js and GraphQL communities. Here's why this distinction exists and what you can do about it:
Understanding the Separation
Prisma Schema:
Purpose: Defines your database schema. It is focused on how the data is stored in your database.
Use Cases: Models database tables and relationships, and is used by Prisma to generate type-safe database access code.
Syntax: Prisma-specific syntax that directly maps to the database, including data types and constraints.
Nexus Schema:
Purpose: Defines your GraphQL API schema. It is focused on how clients interact with your data.
Use Cases: Determines the types, queries, and mutations available via your GraphQL endpoint.
Syntax: Uses JavaScript/TypeScript DSL (Domain Specific Language) to define GraphQL types and operations, making use of the flexibility and expressiveness of GraphQL.
Reasons For Separate Schemas
Separation of Concerns: Database schema defines how data is stored, while GraphQL schema defines how data is served and consumed. These are inherently different domains.
Flexibility in API Design: Allows for more control over exposure of database internals. For example, sensitive fields stored in the database can be hidden from the API, or you can aggregate fields or expose complex relationships differently.
Independent Evolution: Changes in the database schema (such as denormalization for performance) may not always require changes in the API schema.
Options for Single Source of Truth
Nexus Prisma Plugin:
Functionality: Simplifies the process of generating Nexus types directly from your Prisma models.
Usage: Allows you to infer types in your Nexus schema from your Prisma schema, reducing duplication.
Note: You still define the GraphQL-specific parts separately, such as queries and mutations, but field definitions are simplified.
GraphQL Code Generator:
Functionality: Can generate TypeScript types for your GraphQL schema, ensuring type safety across your Prisma and GraphQL layers.
Usage: Automatically generates types for your GraphQL operations based on your schema and queries.
Prisma Mappers/Custom Generators:
Community or self-published code generators that can translate Prisma models to GraphQL types automatically, further reducing boilerplate. However, these are less common and may need custom implementation.
Conclusion
While having two schemas might seem redundant, it provides a clear separation between database operations and API design, fostering clean architecture principles. Tools like the Nexus Prisma Plugin help bridge some of this gap by automatically linking your Prisma models to Nexus types, offering a more integrated approach.
When adding a new table, like a posts table, and you want to seed it with initial data for development purposes, Prisma provides a convenient way to do so using a seeding script. This script can programmatically populate your database with sample data. Here's how you can set it up:
Step-by-Step Guide to Seeding with Prisma
Define Your Prisma Model
In your prisma/schema.prisma file, define the Post model:
prisma
model Post {
id Int @id @default(autoincrement())
title String
content String?
published Boolean @default(false)
authorId Int
author User @relation(fields: [authorId], references: [id])
}
Migrate Your Database
After defining your model, apply the migration to your database:
bash
npx prisma migrate dev --name add_posts
Create a Seed Script
Prisma seeds the database using a script that you define in your project. Create a new script within your project, typically in a directory like prisma/seed.ts:
typescript
// prisma/seed.ts
import { PrismaClient } from '@prisma/client'
const prisma = new PrismaClient()
async function main() {
// Example: Create a user for associating posts
const user = await prisma.user.create({
data: {
email: 'johndoe@example.com',
name: 'John Doe',
},
})
const posts = [
{
title: 'First Post',
content: 'This is the first post',
published: true,
authorId: user.id,
},
{
title: 'Second Post',
content: 'This is the second post',
published: false,
authorId: user.id,
},
]
await prisma.post.createMany({
data: posts,
})
console.log('Seeding completed')
}
main()
.catch(e => {
console.error(e)
process.exit(1)
})
.finally(async () => {
await prisma.$disconnect()
})
Update Your package.json
Add a script in your package.json to execute the seed script:
json
"scripts": {
"seed": "ts-node prisma/seed.ts"
}
If you don't already have ts-node installed, you can add it to your project:
bash
npm install ts-node --save-dev
Run the Seed Script
With everything set up, execute the seed script using:
bash
npm run seed
This command will populate your database with initial data for the posts and any other tables defined in your seed script.
Best Practices for Seeding
Environment Specific Seeding: Be mindful that seeding scripts should cater to development environments and should not be used in production as they might insert dummy data.
Idempotent Seeding: Ensure your seed script can be run multiple times without causing conflicts or duplication, particularly if you are resetting databases frequently during development.
Data Integrity: When referring to foreign keys (like authorId in posts), ensure that referenced entities exist. This might require creating required parent entities (e.g., User) beforehand in the script.
Certainly! When seeding a large number of records like 10,000, you can use libraries such as Faker to generate random data. Faker provides a variety of methods to generate random data like names, addresses, dates, etc., which can be very useful for creating realistic test data.
Here’s how you can use Faker to generate random values for seeding:
Step-by-Step Guide to Using Faker with Prisma
Install Faker
First, you'll need to install Faker in your project:
bash
npm install @faker-js/faker
Set Up Your Seed Script
You can now modify your seed script to use Faker to generate random data:
typescript
// prisma/seed.ts
import { PrismaClient } from '@prisma/client'
import { faker } from '@faker-js/faker'
const prisma = new PrismaClient()
async function main() {
// Create a few users to serve as authors
const authors = []
for (let i = 0; i < 10; i++) {
const user = await prisma.user.create({
data: {
email: faker.internet.email(),
name: faker.name.fullName(),
},
})
authors.push(user)
}
// Generate 10k random posts
const postsData = Array.from({ length: 10000 }).map(() => ({
title: faker.lorem.sentence(),
content: faker.lorem.paragraph(),
published: faker.datatype.boolean(),
authorId: authors[Math.floor(Math.random() * authors.length)].id,
}))
// Batch the creation of posts for better performance
for (let i = 0; i < postsData.length; i += 1000) {
const batch = postsData.slice(i, i + 1000)
await prisma.post.createMany({
data: batch,
})
}
console.log('Seeding completed')
}
main()
.catch(e => {
console.error(e)
process.exit(1)
})
.finally(async () => {
await prisma.$disconnect()
})
Run the Seed Script
Execute the script to populate your database with random data:
bash
npm run seed
Performance Considerations
Batching: When dealing with a large number of records, it's efficient to use createMany in batches (like 1,000 records at a time) to reduce the number of database transactions and improve performance.
Database Backpressure: Ensure your database can handle the volume of data you're writing. Running too many operations at once may cause the database to throttle your requests or lead to slow performance.
Conclusion
By using Faker, you can quickly and efficiently populate your database with a large volume of test data that can mimic real-world scenarios. This setup is ideally suited for testing endpoints, performance benchmarking, and other development needs.