@dataql/prisma-adapter
Version:
Prisma adapter for DataQL with zero API changes
321 lines (284 loc) โข 7.61 kB
text/typescript
import { createPrismaClient } from "@dataql/prisma-adapter";
// Define schemas using DataQL format (converted from Prisma schema)
const schemas = {
user: {
id: { type: "ID", required: true },
email: { type: "String", required: true, unique: true },
name: { type: "String" },
age: { type: "Int" },
isActive: { type: "Boolean", default: true },
profile: {
type: "object",
properties: {
bio: { type: "String" },
website: { type: "String" },
avatarUrl: { type: "String" },
},
},
createdAt: { type: "Date", default: "now" },
updatedAt: { type: "Date", default: "now" },
},
post: {
id: { type: "ID", required: true },
title: { type: "String", required: true },
content: { type: "String" },
published: { type: "Boolean", default: false },
authorId: { type: "ID", required: true, ref: "user" },
tags: { type: "array", items: { type: "String" } },
publishedAt: { type: "Date" },
createdAt: { type: "Date", default: "now" },
updatedAt: { type: "Date", default: "now" },
},
category: {
id: { type: "ID", required: true },
name: { type: "String", required: true },
description: { type: "String" },
createdAt: { type: "Date", default: "now" },
},
};
// TypeScript interfaces for type safety
interface User {
id: string;
email: string;
name?: string;
age?: number;
isActive?: boolean;
profile?: {
bio?: string;
website?: string;
avatarUrl?: string;
};
createdAt?: Date;
updatedAt?: Date;
}
interface Post {
id: string;
title: string;
content?: string;
published?: boolean;
authorId: string;
tags?: string[];
publishedAt?: Date;
createdAt?: Date;
updatedAt?: Date;
}
interface Category {
id: string;
name: string;
description?: string;
createdAt?: Date;
}
async function main() {
console.log("๐ DataQL Prisma Adapter Example");
// Create Prisma client with DataQL backend
const prisma = createPrismaClient<{
user: User;
post: Post;
category: Category;
}>(
{
// DataQL automatically handles routing
appToken: "your-app-token",
env: "dev", // Use 'prod' for production
log: ["query", "error"],
},
schemas
);
console.log("โ
Connected to DataQL");
// Create a user with nested data
const user = await prisma.user.create({
data: {
email: "john@example.com",
name: "John Doe",
age: 30,
profile: {
bio: "Software developer passionate about DataQL",
website: "https://johndoe.dev",
avatarUrl: "https://example.com/avatar.jpg",
},
},
});
console.log("โ
Created user:", user);
// Create multiple posts
const posts = await prisma.post.createMany({
data: [
{
title: "Getting Started with DataQL",
content:
"DataQL provides a powerful offline-first database solution that seamlessly syncs data across devices and regions.",
published: true,
authorId: user.id,
tags: ["tutorial", "getting-started", "dataql"],
publishedAt: new Date(),
},
{
title: "Advanced DataQL Features",
content:
"Explore real-time sync, multi-region support, and offline capabilities.",
published: false,
authorId: user.id,
tags: ["advanced", "features", "dataql"],
},
{
title: "Migrating from Prisma to DataQL",
content:
"Step-by-step guide for migrating your existing Prisma application to DataQL.",
published: true,
authorId: user.id,
tags: ["migration", "prisma", "dataql"],
},
],
});
console.log("โ
Created posts:", posts);
// Query with filters and pagination
const publishedPosts = await prisma.post.findMany({
where: {
published: true,
authorId: user.id,
},
select: {
id: true,
title: true,
content: true,
tags: true,
publishedAt: true,
},
orderBy: {
publishedAt: "desc",
},
take: 10,
});
console.log("๐ Published posts:", publishedPosts);
// Find unique user
const foundUser = await prisma.user.findUnique({
where: {
email: "john@example.com",
},
include: {
// Basic include support
},
});
console.log("๐ Found user:", foundUser);
// Complex filtering
const recentActiveUsers = await prisma.user.findMany({
where: {
isActive: true,
age: {
gte: 18,
lte: 65,
},
email: {
contains: "@example.com",
},
},
orderBy: {
createdAt: "desc",
},
take: 5,
});
console.log("๐ฅ Recent active users:", recentActiveUsers);
// Update operations
const updatedUser = await prisma.user.update({
where: {
id: user.id,
},
data: {
age: 31,
profile: {
bio: "Senior software developer with expertise in DataQL",
},
},
});
console.log("๐ Updated user:", updatedUser);
// Upsert operation
const upsertedPost = await prisma.post.upsert({
where: {
id: "non-existent-id",
},
create: {
title: "DataQL Best Practices",
content: "Learn the best practices for using DataQL in production.",
published: true,
authorId: user.id,
tags: ["best-practices", "dataql"],
},
update: {
title: "Updated: DataQL Best Practices",
},
});
console.log("๐ Upserted post:", upsertedPost);
// Aggregation operations
const postCount = await prisma.post.count({
where: {
published: true,
},
});
console.log("๐ Published post count:", postCount);
// Transaction example
const transactionResult = await prisma.$transaction(async (tx) => {
// Create a category
const category = await tx.category.create({
data: {
name: "Technology",
description: "Posts about technology and programming",
},
});
// Create a user
const newUser = await tx.user.create({
data: {
email: "jane@example.com",
name: "Jane Smith",
age: 28,
},
});
// Create a post
const newPost = await tx.post.create({
data: {
title: "Introduction to React",
content: "Learn the basics of React development.",
published: true,
authorId: newUser.id,
tags: ["react", "javascript", "frontend"],
},
});
return { category, user: newUser, post: newPost };
});
console.log("๐พ Transaction result:", transactionResult);
// Batch operations
const batchResult = await prisma.$transaction([
prisma.post.updateMany({
where: { published: false },
data: { published: true },
}),
prisma.user.updateMany({
where: { isActive: { equals: undefined } },
data: { isActive: true },
}),
]);
console.log("๐ฆ Batch operation results:", batchResult);
// Delete operations
const deletedPosts = await prisma.post.deleteMany({
where: {
published: false,
},
});
console.log("๐๏ธ Deleted unpublished posts:", deletedPosts);
// Cleanup: Delete the test user
const deletedUser = await prisma.user.delete({
where: {
id: user.id,
},
});
console.log("๐งน Cleaned up test user:", deletedUser.email);
console.log("๐ Prisma adapter example completed successfully!");
}
// Handle errors
main()
.catch((error) => {
console.error("โ Error:", error);
process.exit(1);
})
.finally(async () => {
// Disconnect from DataQL
process.exit(0);
});