Overview
Add a database layer to your Fragment
The @fragno-dev/db package provides an optional database layer for Fragments that need
persistent storage. This allows Fragment authors to define a type-safe schema while users provide
their existing database connection.
Key Features
- Schema Definition: Define tables, columns, indexes, and relations
- Type-Safe ORM: Full TypeScript type inference for queries
- User-Owned Database: Fragment users provide their database adapter
- ORM Agnostic: Works with Kysely or Drizzle
- Automatic Migrations: Schema versioning and migration generation
- Namespaced Tables: Prevents conflicts with user tables
Optional Feature
Database integration is completely optional. Only add it if your Fragment needs persistent storage. Simple Fragments can use in-memory storage or rely on external APIs instead.
Installation
npm install @fragno-dev/dbCreating a Database Fragment
Use defineFragmentWithDatabase() from the @fragno-dev/db package instead of defineFragment()
from the @fragno-dev/core package.
You can then use the .withDatabase(schema) method to attach your schema to the Fragment.
import { createFragment } from "@fragno-dev/core";
import { defineFragmentWithDatabase, type FragnoPublicConfigWithDatabase } from "@fragno-dev/db";
import { commentSchema } from "./schema";
export interface CommentFragmentConfig {
maxCommentsPerPost?: number;
}
const commentFragmentDef = defineFragmentWithDatabase<CommentFragmentConfig>("comment-fragment")
.withDatabase(commentSchema)
.providesService(({ db }) => {
return {
createComment: async (data) => {
const id = await db.create("comment", data);
return { id: id.toJSON(), ...data };
},
getComments: async (postId: string) => {
return db.find("comment", (b) => b.where((eb) => eb("postId", "=", postId)));
},
};
});
// Make sure to allow your users to provide their database adapter
export function createCommentFragment(
config: CommentFragmentConfig = {},
options: FragnoPublicConfigWithDatabase,
) {
return createFragment(commentFragmentDef, config, [], options);
}Make sure to allow your users to provide their database adapter
Your Fragment's creation function must accept FragnoPublicConfigWithDatabase, or
DatabaseAdapter in the options.
Next Steps
- Learn about Defining Schemas with the append-only log approach
- Explore the Querying API for CRUD operations
- See the example-fragments/fragno-db-library for a complete example