@onkit/bean
v0.1.0
Published
Lightweight SDK for Onkit MongoDB proxy — works in Workers, Edge, Node, and browsers
Readme
@onkit/bean
Lightweight SDK for Onkit MongoDB proxy. Works everywhere fetch works — Cloudflare Workers, Vercel Edge, Deno, Node.js, and browsers.
Zero dependencies. ~2KB minified.
Install
npm install @onkit/beanQuick Start
import { createOnkit } from "@onkit/bean";
const db = createOnkit({
url: "https://bean.onkit.xyz",
key: "sk_abc123...",
});
// Get a collection handle
const users = db.collection("User");
// Find documents
const { data, cursor } = await users.find({
filter: { active: true },
sort: { createdAt: -1 },
limit: 20,
});
// Paginate
if (cursor.hasMore) {
const page2 = await users.find({ cursor: cursor.next });
}
// Find one
const user = await users.findOne({ email: "[email protected]" });
// Count
const total = await users.count({ active: true });
// Create
const newUser = await users.create({
name: "Jane",
email: "[email protected]",
});
// Update
await users.updateOne(
{ _id: "abc123" },
{ $set: { name: "Jane Doe" } }
);
// Delete
await users.deleteOne({ _id: "abc123" });
// Aggregate
const stats = await users.aggregate([
{ $group: { _id: "$role", count: { $sum: 1 } } },
]);
// Distinct
const roles = await users.distinct("role", { active: true });
// Bulk write
await users.bulkWrite([
{ insertOne: { document: { name: "Alice" } } },
{ updateOne: { filter: { name: "Bob" }, update: { $set: { active: true } } } },
]);Cloudflare Worker Example
import { createOnkit } from "@onkit/bean";
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const db = createOnkit({
url: env.ONKIT_URL,
key: env.ONKIT_KEY,
});
const products = db.collection("Product");
const { data } = await products.find({
filter: { inStock: true },
limit: 50,
});
return Response.json(data);
},
};TypeScript
type User = {
_id: string;
name: string;
email: string;
active: boolean;
};
const users = db.collection<User>("User");
const user = await users.findOne({ email: "[email protected]" });
// user is User | nullError Handling
import { OnkitError } from "@onkit/bean";
try {
await users.findOne({ _id: "invalid" });
} catch (err) {
if (err instanceof OnkitError) {
console.log(err.code); // "UNAUTHORIZED"
console.log(err.message); // "Invalid API key"
console.log(err.status); // 401
}
}API
createOnkit(config)
| Option | Type | Description |
|---|---|---|
| url | string | Onkit proxy URL |
| key | string | API key (pk_ or sk_ prefix) |
| fetch | typeof fetch | Custom fetch (optional) |
collection.find(options?)
| Option | Type | Description |
|---|---|---|
| filter | object | MongoDB filter |
| projection | object | Field selection ({ name: 1 }) |
| sort | object | Sort order ({ createdAt: -1 }) |
| limit | number | Max results (1-100) |
| cursor | string | Pagination cursor from previous result |
