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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@promakeai/dbreact

v1.6.0

Published

React client for schema-driven multi-language database

Readme

@promakeai/dbreact

React hooks and providers for schema-driven, multi-language databases. Type-safe, with automatic translation support.

Features

  • Type-Safe Hooks - Generic React hooks with generated TypeScript types
  • Multi-Language Support - Automatic translation queries with fallback
  • Browser SQLite - sql.js WASM adapter for offline-first apps
  • REST API Adapter - Remote database access with dynamic Bearer auth
  • React Query Integration - Built-in caching, loading states, optimistic updates
  • Realtime (opt-in) - One SSE connection auto-refreshes queries on server table changes
  • Zero-Config Language Switching - Change language, queries refetch automatically
  • MongoDB-Style Queries - Intuitive filter syntax ($gt, $in, $like, $contains, etc.)

Installation

npm install @promakeai/dbreact @tanstack/react-query

Peer Dependencies:

  • react >= 18.0.0
  • @tanstack/react-query >= 5.0.0

Quick Start

1. Setup Adapter

import { SqliteAdapter } from '@promakeai/dbreact';
import { parseJSONSchema } from '@promakeai/dbreact';
import schemaJson from './schema.json';

const schema = parseJSONSchema(schemaJson as any);

const adapter = new SqliteAdapter({
  storageKey: 'myapp-db',  // localStorage key for persistence
  schema,
});

2. Wrap App with Provider

import { DbProvider } from '@promakeai/dbreact';

function App() {
  const [lang, setLang] = useState('en');

  return (
    <DbProvider
      adapter={adapter}
      lang={lang}
      fallbackLang="en"
      autoConnect={true}
    >
      <MyApp />
    </DbProvider>
  );
}

3. Use Hooks

import { useDbList, useDbGet, useDbCreate } from '@promakeai/dbreact';

function ProductList() {
  // List with filters
  const { data: products, isLoading } = useDbList('products', {
    where: { stock: { $gt: 0 } },
    orderBy: [{ field: 'name', direction: 'ASC' }],
    limit: 20,
  });

  // Create mutation
  const createProduct = useDbCreate('products');

  const handleCreate = () => {
    createProduct.mutate({
      sku: 'NEW-001',
      price: 99.99,
    });
  };

  if (isLoading) return <div>Loading...</div>;

  return (
    <div>
      {products?.map(p => <ProductCard key={p.id} product={p} />)}
      <button onClick={handleCreate}>Add Product</button>
    </div>
  );
}

API Reference

DbProvider

Main provider component that wraps your application.

<DbProvider
  adapter={adapter}
  schema={schema}
  lang="tr"
  fallbackLang="en"
  autoConnect={true}
>
  <App />
</DbProvider>

Props:

| Prop | Type | Required | Default | Description | |------|------|----------|---------|-------------| | adapter | IDataAdapter | Yes | - | Database adapter instance | | schema | SchemaDefinition | No | - | Enables populate + typed serialization | | lang | string | No | 'en' | Current language code | | fallbackLang | string | No | 'en' | Fallback language | | autoConnect | boolean | No | true | Auto-connect on mount | | queryClient | QueryClient | No | Internal | Provide a custom React Query client | | realtime | RealtimeConfig | No | - | Opt-in realtime auto-refresh (see below) | | children | ReactNode | Yes | - | Child components |


Realtime (opt-in)

When the backend supports the realtime SSE stream, pass a realtime prop and dbreact opens ONE long-lived connection per tab. On each server change event it invalidates any active query whose changed table sits in the leading table-position run of its key (the run of table names up to the "list" / "single" discriminator), so every useDbList / useDbGet for that table, plus any multi-table derived query that lists it as a dependency, refetches automatically. A table name that only appears later in a key (for example inside a where or populate value) does not trigger a refetch. This is fully opt-in: when the prop is absent, no connection is opened and behavior is byte-identical to a build without realtime support.

Reserved table names. "list" and "single" are reserved key discriminators. A table literally named list or single sits in the same position as the discriminator, so its change events would not invalidate any query. Do not name a table list or single.

<DbProvider
  adapter={adapter}
  realtime={{
    url: `${API_BASE}/realtime`,
    getToken: () => localStorage.getItem("token"),
  }}
>
  <App />
</DbProvider>

RealtimeConfig:

| Field | Type | Required | Description | |------|------|----------|-------------| | url | string | Yes | Full URL of the realtime SSE endpoint | | getToken | () => string \| null | No | Bearer token getter, called per connect | | heartbeatTimeoutMs | number | No | Watchdog window (default 35000) | | fetch | typeof fetch | No | Custom fetch (tests / SSR) |

It is fail-safe: pointing at an old backend with no /realtime route never throws into React and never breaks useDbList / useDbGet. After a few failed attempts the client goes dormant and stops retrying until a remount. The single connection survives React strict-mode double-mount and re-renders, reconnects on involuntary drops (proxy idle-kill / heartbeat timeout), and tears down cleanly when the provider unmounts.


Query Hooks

useDbList

Fetch multiple records with filtering, pagination, and sorting.

const { data, isLoading, error, refetch } = useDbList<Product>('products', {
  where: { stock: { $gt: 0 } },
  orderBy: [{ field: 'price', direction: 'DESC' }],
  limit: 20,
  offset: 0,
  enabled: true,
});

Options:

| Option | Type | Description | |--------|------|-------------| | where | object | MongoDB-style filter conditions | | orderBy | array | Sort order [{ field, direction }] | | limit | number | Max records to return | | offset | number | Skip records | | populate | PopulateOption | Resolve foreign key references (string, array, or object) | | q | string | Free-text search across the table's text columns | | enabled | boolean | Enable/disable query |

Those seven keys are the complete set. Any other key is still forwarded to the adapter unchanged (and enters the react-query cache key, so two call sites differing only in it are separate cache entries), but in development useDbList logs a one-time console.warn naming it (and the option it was probably meant to be, e.g. filters -> where). Silence in production.

Two exceptions to "forwarded unchanged": lang and fallbackLang are supplied by the hook itself, so a value passed there is overwritten and never reaches the adapter - useDbList builds { ...options, lang, fallbackLang }, writing the provider's values after the spread. Set the language on DbProvider (lang / fallbackLang) or with useDbLang().setLang(); the warning says so.

"Development" is decided by process.env.NODE_ENV, written as that literal member expression so a bundler's define (webpack, Next, esbuild, Vite) substitutes it at build time. Rollup core has no constant substitution - its define is the AMD module function name - so a plain Rollup build needs @rollup/plugin-replace or it falls through to the no-signal default below. When no process exists and nothing was substituted, import.meta.env.PROD / .DEV is consulted instead. If neither signal is present the diagnostic stays on, the same default React uses.

useDbGet

Fetch single record by ID.

const { data: product, isLoading } = useDbGet<Product>('products', productId, {
  populate: ['categoryId'],
  enabled: !!productId,
});

Find-one style (by where clause):

const { data: product } = useDbGet<Product>('products', {
  where: { slug },
  enabled: !!slug, // gates on the same value the `where` is built from
  populate: { categoryId: true },
});

useDbGet has two option surfaces, each with its own complete key set:

| Form | Valid keys | |---|---| | find-one, useDbGet(table, { where, ... }) | where, enabled, populate | | by ID, useDbGet(table, id, { ... }) | enabled, populate |

orderBy / limit / offset / q are list-only - they are not valid on either form. Unlike useDbList, useDbGet builds its query explicitly, so an unknown key here is dropped rather than forwarded to the adapter; in development it produces the same one-time console.warn. lang / fallbackLang are the same exception as above - the hook always sends the provider's language.

Do not mix the forms. In the find-one form the third argument is ignored completely - enabled and populate are read from the options object - so useDbGet('products', { where: { slug } }, { enabled: !!slug }) does not gate the query; it runs immediately against where: { slug: undefined }. Put those keys inside the options object instead. Development warns once per table when a third argument with keys in it is passed in find-one form. An empty {} ignored nothing, so it stays silent rather than spending that table's one warning.

One extra trap: the two forms are told apart by whether the second argument has a where key. An options object without where is therefore read as a record ID, and the query becomes where: { id: <that object> } - which cannot identify a row. On the SQLite adapter it does not even build: buildWhereClause reads that inner object's keys as operators, so useDbGet('products', { enabled: false }) throws Unknown operator: enabled and the query fails rather than returning your record. In development useDbGet warns once per table when that happens.

And the worst one, because it returns the wrong record rather than none: a conditional where must be paired with enabled.

// WRONG - returns the first row of `products`, typed as a real product
const { data } = useDbGet<Product>('products', { where: slug ? { slug } : undefined });

// RIGHT
const { data } = useDbGet<Product>('products', {
  where: slug ? { slug } : undefined,
  enabled: !!slug,
});

"where" in options tests the key, not the value, so the first call is still find-one and enabled defaults to true. findOne is list(table, { ...options, limit: 1 }) and buildWhereClause emits no SQL for an empty where (undefined and {} alike), so the query degrades to SELECT ... LIMIT 1. Development warns once per table - but only when the query would actually run, so the gated RIGHT form above stays silent. This one is only diagnosed, not prevented - the warning is dev-only, so the wrong row still reaches a production build.

That is deliberate, not a pending fix. IDataAdapter.findOne(table, options?) takes its options optionally and is specified as "find first record matching query (like Mongoose findOne)", so an unfiltered findOne returning the first row is the documented contract - the same semantics Mongoose and Prisma's findFirst have - and it is covered by a test. An empty where is a valid query, not a malformed one, so the guard belongs at the call site: pair a conditional where with enabled, the way the ID form is already gated on id !== undefined.


Mutation Hooks

useDbCreate

Create a new record.

const createProduct = useDbCreate<Product>('products');

createProduct.mutate(
  { sku: 'NEW-001', price: 99.99 },
  {
    onSuccess: (data) => console.log('Created:', data),
    onError: (error) => console.error(error),
  }
);

useDbUpdate

Update an existing record.

const updateProduct = useDbUpdate<Product>('products');

updateProduct.mutate(
  { id: productId, data: { price: 89.99 } },
  {
    onSuccess: () => console.log('Updated'),
  }
);

useDbDelete

Delete a record.

const deleteProduct = useDbDelete('products');

deleteProduct.mutate(productId, {
  onSuccess: () => console.log('Deleted'),
});

Context Hooks

useDb

Access database connection status.

const { adapter, isConnected, error } = useDb();

if (!isConnected) return <div>Connecting...</div>;

useAdapter

Access adapter directly for raw queries.

const adapter = useAdapter();

const handleRawQuery = async () => {
  const results = await adapter.raw('SELECT * FROM products WHERE price > ?', [100]);
  console.log(results);
};

useDbLang

Access and control language settings.

const { lang, fallbackLang, setLang } = useDbLang();

// Language switcher
<select value={lang} onChange={e => setLang(e.target.value)}>
  <option value="en">English</option>
  <option value="tr">Turkce</option>
  <option value="de">Deutsch</option>
</select>

SqliteAdapter

Browser-based SQLite storage using sql.js (WebAssembly).

const adapter = new SqliteAdapter({
  storageKey: 'myapp-db',     // localStorage key for persistence
  schema: mySchema,           // Optional: schema definition
  initialData: seedData,      // Optional: initial seed data
});

Features:

  • Automatic persistence to localStorage
  • Full SQL support
  • Works offline
  • WASM-based (no native dependencies)

Limitations:

  • Data stored in browser only
  • localStorage limit: ~5-10MB (browser dependent)
  • Best for < 10,000 records

RestAdapter

REST API adapter for remote database access. Supports static tokens and dynamic getToken callbacks.

import { RestAdapter } from '@promakeai/dbreact';

const adapter = new RestAdapter({
  baseUrl: 'https://api.example.com',
  databasePrefix: '/database',
  schema,
  defaultLang: 'en',
  // Dynamic token — called on every request
  getToken: () => {
    try {
      const raw = localStorage.getItem('auth-storage');
      return raw ? JSON.parse(raw)?.state?.tokens?.accessToken ?? null : null;
    } catch { return null; }
  },
});

Config:

| Option | Type | Required | Description | |--------|------|----------|-------------| | baseUrl | string | Yes | API base URL | | databasePrefix | string | No | Endpoint prefix (default: /database) | | token | string | No | Static Bearer token | | getToken | () => string \| null | No | Dynamic token getter (priority over token) | | schema | SchemaDefinition | No | Schema for translation support | | defaultLang | string | No | Default language | | headers | Record<string, string> | No | Custom headers | | timeout | number | No | Request timeout in ms (default: 30000) |


Query Options

MongoDB-Style Filters

// Comparison
{ price: { $gt: 100 } }              // > 100
{ price: { $gte: 100 } }             // >= 100
{ price: { $lt: 100 } }              // < 100
{ price: { $lte: 100 } }             // <= 100
{ price: { $ne: 100 } }              // != 100
{ price: { $eq: 100 } }              // = 100

// Array
{ id: { $in: [1, 2, 3] } }           // IN (1, 2, 3)
{ id: { $nin: [1, 2, 3] } }          // NOT IN (1, 2, 3)

// String
{ name: { $like: '%shirt%' } }       // LIKE '%shirt%'
{ name: { $notLike: '%test%' } }     // NOT LIKE '%test%'

// Range
{ price: { $between: [10, 100] } }   // BETWEEN 10 AND 100

// Null
{ description: { $isNull: true } }   // IS NULL
{ description: { $isNull: false } }  // IS NOT NULL

// JSON array contains
{ tags: { $contains: "sale" } }
{ tags: { $containsAny: ["sale", "new"] } }

// Logical
{ $and: [
  { price: { $gt: 50 } },
  { stock: { $gt: 0 } }
]}

{ $or: [
  { category: 'shirts' },
  { category: 'pants' }
]}

{ $not: { price: { $lt: 100 } } }    // NOT (price < 100)

Query Interface

interface QueryOptions {
  where?: Record<string, unknown>;
  orderBy?: Array<{
    field: string;
    direction: 'ASC' | 'DESC';
  }>;
  limit?: number;
  offset?: number;
  populate?: PopulateOption;
  lang?: string;
  fallbackLang?: string;
}

Multi-Language Support

Schema with Translatable Fields

{
  "languages": ["en", "tr", "de"],
  "tables": {
    "products": {
      "id": { "type": "id" },
      "price": { "type": "decimal" },
      "name": { "type": "string", "translatable": true },
      "description": { "type": "text", "translatable": true }
    }
  }
}

Automatic Translation

Queries automatically use the current language from DbProvider:

function ProductList() {
  // Automatically fetches in current language
  const { data: products } = useDbList('products');

  // products[0].name is in Turkish if lang='tr'
  // Falls back to English if Turkish translation missing
}

Language Switching

When you change language, React Query automatically refetches all queries:

function LanguageSwitcher() {
  const { lang, setLang } = useDbLang();

  return (
    <select value={lang} onChange={e => setLang(e.target.value)}>
      <option value="en">English</option>
      <option value="tr">Turkce</option>
    </select>
  );
}

Generated Types + Generic Hooks

Generate runtime schema and TypeScript interfaces:

dbcli generate --schema ./schema.json --output ./src/db

dbcli generate writes schema.json and types.ts. React hooks are imported from @promakeai/dbreact:

import { useDbList, useDbGet, useDbCreate } from '@promakeai/dbreact';
import type { DbProduct, DbProductInput } from './db/types';

function ProductManager() {
  const { data: products } = useDbList<DbProduct>('products', {
    where: { stock: { $gt: 0 } },
  });

  const { data: product } = useDbGet<DbProduct>('products', 1);

  const createProduct = useDbCreate<DbProduct, DbProductInput>('products');

  return null;
}

Advanced Usage

Custom React Query Options

const { data } = useDbList('products', {
  where: { active: true },
  limit: 50,
});

Direct Adapter Access

For complex queries not covered by hooks:

function AdvancedSearch() {
  const adapter = useAdapter();
  const [results, setResults] = useState([]);

  const handleSearch = async (query: string) => {
    const products = await adapter.list('products', {
      where: {
        $or: [
          { name: { $like: `%${query}%` } },
          { description: { $like: `%${query}%` } },
        ],
      },
      limit: 50,
    });
    setResults(products);
  };

  return <SearchInput onSearch={handleSearch} />;
}

Optimistic Updates

function ProductPrice({ product }) {
  const queryClient = useQueryClient();
  const updateProduct = useDbUpdate('products');

  const handlePriceChange = async (newPrice: number) => {
    // Optimistic update
    queryClient.setQueryData(
      ['products', 'detail', product.id],
      { ...product, price: newPrice }
    );

    await updateProduct.mutateAsync({
      id: product.id,
      data: { price: newPrice },
    });
  };

  return <PriceInput value={product.price} onChange={handlePriceChange} />;
}

Examples

E-Commerce Product List

function Shop() {
  const { lang } = useDbLang();
  const [category, setCategory] = useState(null);

  const { data: products, isLoading } = useDbList('products', {
    where: category ? { categoryId: category } : {},
    orderBy: [{ field: 'name', direction: 'ASC' }],
  });

  if (isLoading) return <Spinner />;

  return (
    <div>
      <CategoryFilter onSelect={setCategory} />
      <ProductGrid products={products} />
    </div>
  );
}

Multi-Language Blog

function BlogPost({ slug }: { slug: string }) {
  const { data: posts } = useDbList('posts', {
    where: { slug, published: true },
    limit: 1,
  });

  const post = posts?.[0];
  if (!post) return <NotFound />;

  return (
    <article>
      <h1>{post.title}</h1>         {/* Auto-translated */}
      <div>{post.content}</div>     {/* Auto-translated */}
    </article>
  );
}

Real-Time Search

function ProductSearch() {
  const adapter = useAdapter();
  const [query, setQuery] = useState('');

  const { data: results } = useQuery({
    queryKey: ['search', query],
    queryFn: () => adapter.list('products', {
      where: {
        $or: [
          { name: { $like: `%${query}%` } },
          { sku: { $like: `%${query}%` } },
        ],
      },
      limit: 10,
    }),
    enabled: query.length > 2,
  });

  return (
    <div>
      <input value={query} onChange={e => setQuery(e.target.value)} />
      <SearchResults results={results} />
    </div>
  );
}

TypeScript Support

Full TypeScript support with generated types:

import type { DbProduct, DbProductInput } from './db/types';

// Type-safe queries
const products: DbProduct[] = await adapter.list('products');

// Type-safe creates
const newProduct: DbProductInput = {
  sku: 'SHIRT-001',
  price: 99.99,
};

await adapter.create('products', newProduct);

Performance Tips

  1. Use pagination for large datasets:

    const { data } = useDbList('products', { limit: 20, offset: page * 20 });
  2. Enable query conditionally:

    const { data } = useDbGet('products', id, { enabled: !!id });
  3. Prefetch next page:

    queryClient.prefetchQuery({
      queryKey: ['products', 'list', { offset: (page + 1) * 20 }],
      queryFn: () => adapter.list('products', { offset: (page + 1) * 20 }),
    });

Troubleshooting

Production crash: jsxDEV is not a function

  • Run bun run test:build-runtime before publishing.
  • This verifies dist/index.js does not include react/jsx-dev-runtime.

"useDbLang must be used within a DbProvider"

  • Ensure component is wrapped in DbProvider

Queries return empty results

  • Check adapter is connected: const { isConnected } = useDb()
  • Verify data exists in database
  • Check query filters are correct

Translations not working

  • Ensure schema has .translatable() fields
  • Run dbcli generate to create translation tables
  • Check translation records exist in {table}_translations

Related Packages

License

MIT