npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

watermelon-repository

v1.0.4

Published

Generic Repository Pattern for WatermelonDB

Readme

🍉 watermelon-repository

NPM JavaScript Style Guide npm

A lightweight Repository Layer for WatermelonDB.
Provides a generic CRUD API, prepare* helpers for batch writes, and follows the Singleton Repository Pattern.

✨ Features

  • ✅ Simple CRUD (create, update, delete, destroy)
  • ✅ Supports prepareCreate / prepareUpdate / prepareDelete for batch operations
  • Singleton pattern (only one repository instance per model)
  • Static Database Injection (set DB once at app bootstrap)
  • ✅ Works seamlessly with React Native + WatermelonDB

📦 Installation

npm install watermelon-repository
# or
yarn add watermelon-repository

🚀 Usage

1. Setup Database at App Bootstrap

import { Database } from "@nozbe/watermelondb";
import SQLiteAdapter from "@nozbe/watermelondb/adapters/sqlite";
import { appSchema, tableSchema } from "@nozbe/watermelondb";
import BaseRepository from "watermelon-repository";
import { User } from "./models/User";

// Define adapter
const adapter = new SQLiteAdapter({
  schema: appSchema({
    version: 1,
    tables: [
      tableSchema({
        name: "users",
        columns: [{ name: "name", type: "string" }],
      }),
    ],
  }),
});

// Initialize database
const database = new Database({
  adapter,
  modelClasses: [User],
});

// Inject DB globally (done once)
BaseRepository.setDatabase(database);

2. Create Your Repository

import BaseRepository from "watermelon-repository";
import { User } from "../models/User";

export default class UserRepository extends BaseRepository<User> {
  constructor() {
    super(User);
  }
}

3. Use Repository Anywhere

import UserRepository from "../repositories/UserRepository";

async function demo() {
  const userRepo = UserRepository.instance();

  // CREATE
  const user = await userRepo.create({ name: "Ali" });

  // READ
  const users = await userRepo.getAll();

  // UPDATE
  await userRepo.update(user.id, { name: "Omar" });

  // DELETE (soft)
  await userRepo.delete(user.id);

  // DESTROY (hard)
  await userRepo.destroy(user.id);
}

🛠 API Reference

Static

  • BaseRepository.setDatabase(db: Database) → Set global DB instance
  • BaseRepository.getDatabase(): Database → Get the global DB instance
  • UserRepository.instance() → Singleton instance

CRUD

  • create(data: Partial<T>): Promise<T>
  • update(id: string, data: Partial<T>): Promise<T | null>
  • delete(id: string): Promise<void> → Soft delete
  • destroy(id: string): Promise<void> → Hard delete

Prepare Methods (for batch writes)

  • prepareCreate(data: Partial<T>): T
  • prepareUpdate(record: T, data: Partial<T>): T
  • prepareDelete(record: T): T
  • prepareDestroy(record: T): T

Helpers

  • getById(id: string): Promise<T | null>
  • getAll(whereClause?: any[]): Promise<T[]>

🧪 Testing

We use Jest for testing.

Run tests:

npm test

Example test:

it("should create a user", async () => {
  const user = await userRepo.create({ name: "Ali" } as any);
  expect(user.id).toBeTruthy();
});

4. Using prepare* Methods (Batch Writes)

WatermelonDB supports batching multiple operations into a single DB write.
This library exposes prepare* methods for that.

import UserRepository from "../repositories/UserRepository";
import { database } from "../db"; // your global Database instance

async function batchExample() {
  const userRepo = UserRepository.instance();

  const newUser = userRepo.prepareCreate({ name: "Hasan" });

  const existingUsers = await userRepo.getAll();
  const updatedUser = userRepo.prepareUpdate(existingUsers[0], { name: "Updated Ali" });

  const deletedUser = userRepo.prepareDelete(existingUsers[1]);

  // 🚀 Commit all operations in ONE transaction
  await database.write(async () => {
    await database.batch(newUser, updatedUser, deletedUser);
  });
}

📜 License

MIT © 2025 – Built for React Native + WatermelonDB ❤️