由 kestrel 出售

Ottoman is a feature-rich Object Document Mapper (ODM) for Couchbase and Node.js, offering TypeScript support, a built-in query builder, index management, and extensible schemas with hooks and plugins.
Ottoman is a TypeScript-first ODM for Couchbase, providing schema definition, model lifecycle hooks, query building, and index management on top of the Couchbase Node.js SDK. This block ships the full Ottoman v2 source so you can embed it directly, fork it, or tree-shake it inside a Node.js/Express/NestJS backend that talks to Couchbase Server 7.2+.
exceptions/ - Custom error classes (OttomanError and subtypes)handler/ - CRUD operation handlers: find, store, remove, createMany, removeMany, updateManymodel/ - Core model factory, Document base class, hooks, index builders (N1QL, View, Refdoc), and model utilitiesottoman/ - Top-level Ottoman class and singleton helpers (connect, model, start, close, etc.)plugins/ - Global plugin registration and error handlingquery/ - Fluent N1QL query builder (Query), expression helpers, and type definitionsschema/ - Schema class, built-in field types, validators, and custom type registrationutils/ - Cast strategy, search consistency, query extraction helperscouchbase.ts - Re-exports from the Couchbase SDK used internallyindex.ts - Single-entry barrel re-exporting everything publicnpm install couchbase@^4.4.6
npm install uuid lodash jsonpath
npm install @scarf/scarf
No native build steps are required for Node.js 12+. The Couchbase SDK ships prebuilt binaries; if a binary is unavailable for your platform, node-gyp will attempt a source build — ensure a C++ toolchain is available.
source/ directory into your project, e.g. src/ottoman/source/.tsconfig.json, ensure "moduleResolution": "node", "esModuleInterop": true, "strict": true, and add a path alias if desired:{
"compilerOptions": {
"moduleResolution": "node",
"esModuleInterop": true,
"strict": true,
"paths": {
"ottoman": ["./src/ottoman/source/index.ts"]
}
}
}
启动隔离沙箱并在服务器端直接运行 — 无需本地配置。
此版本的 Tetrees AI Review
This Express backend / api completed archive review. Structure, dependency manifests, documentation, functional source, and common risk patterns were checked by the Tetrees verification pipeline; runtime phases are stated separately.
Deterministic AVCP artifact review
管道 avcp-2026-08-04.1 · SHA-256 d8f5b7d720f6d254…
This version-scoped review deterministically inspects the submitted archive for structure, dependencies, documentation, functional source, and common malicious or high-risk signals. Build and test phases are reported as passed only after an isolated sandbox audition. It is not a guarantee of perfect security.
审查日期 2026年8月4日
将此产品直接导入你的 AI IDE、网页构建器或云端 IDE。
将 Tetrees 连接到兼容的 AI IDE,列出你拥有的产品并获取已验证 ZIP,同时不会开放卖家上传权限。
暂无评价。
Sign in to join the discussion
Loading discussion…
COUCHBASE_URL=couchbase://localhost
COUCHBASE_BUCKET=your-bucket
COUCHBASE_USER=admin
COUCHBASE_PASS=password
In your application entry point, call connect then start before any model operations, and close on graceful shutdown.
If you are using a bundler (esbuild, webpack), mark couchbase and @scarf/scarf as external — they must remain as native Node.js requires.
import { connect } from './ottoman/source';
async function connect(connectString: string, connectOptions?: ConnectOptions): Promise<Ottoman>
Opens a connection to Couchbase using a connection string of the form couchbase://host/bucket@user:password. Returns the default Ottoman instance. Must be awaited before defining models or running queries.
import { model } from './ottoman/source';
function model<T = any>(
name: string,
schema: Schema | Record<string, any>,
options?: ModelOptions
): IModel<T>
Defines and registers a model on the default Ottoman instance. schema can be a Schema instance or a plain object shorthand. options.collectionName overrides the collection used; options.scopeName sets the scope. Returns a constructor whose instances are Document objects.
import { Schema } from './ottoman/source';
class Schema {
constructor(fields: Record<string, any>, options?: SchemaOptions)
add(fields: Record<string, any>): void
index(name: string, fields: string[], options?: object): void
pre(hook: string, fn: Function): void
post(hook: string, fn: Function): void
}
Defines the structure, types, validators, and indexes for a model. Supports embedded documents (EmbedType), references (ReferenceType), custom validators, and lifecycle hooks (pre/post on save, validate, remove).
import { Query } from './ottoman/source';
class Query {
constructor(conditions: IConditionExpr, bucketName: string)
select(expressions?: ISelectType[]): this
where(expr: LogicalWhereExpr): this
limit(n: number): this
offset(n: number): this
orderBy(expr: Record<string, SortType>): this
build(): string
}
Fluent N1QL query builder. Use build() to produce a raw N1QL string you can pass to the Couchbase cluster. Useful when model-level finders do not cover a complex aggregation or join.
import { SearchConsistency } from './ottoman/source';
enum SearchConsistency {
NONE,
LOCAL,
GLOBAL
}
Controls index scan consistency for find and findOne calls. Pass via FindOptions.consistency. Use GLOBAL in tests or write-then-read flows; use NONE for high-throughput reads.
Define a typed User model, persist a document, and retrieve it.
import { connect, model, start, close, Schema } from './ottoman/source';
const userSchema = new Schema({
name: { type: String, required: true },
email: { type: String, required: true },
createdAt: { type: Date, default: () => new Date() },
});
async function main() {
await connect(
`couchbase://${process.env.COUCHBASE_URL}/${process.env.COUCHBASE_BUCKET}` +
`@${process.env.COUCHBASE_USER}:${process.env.COUCHBASE_PASS}`
);
const User = model('User', userSchema);
await start(); // ensures indexes are created
const user = new User({ name: 'Jane Doe', email: 'jane@example.com' });
await user.save();
console.log('Saved user id:', user.id);
const found = await User.findById(user.id);
console.log('Found:', found.name);
await close();
}
main().catch(console.error);
Build and log a parameterised N1QL statement without going through a model.
import { Query, buildWhereClauseExpr } from './ottoman/source';
const conditions = {};
const query = new Query(conditions, 'travel-sample')
.select([{ $field: 'name' }, { $field: 'country' }])
.where({
$and: [
{ type: { $eq: 'airport' } },
{ country: { $like: 'United%' } },
],
})
.orderBy({ name: 'ASC' })
.limit(20)
.offset(0);
const n1ql = query.build();
console.log(n1ql);
// SELECT name, country FROM `travel-sample`
// WHERE (type = "airport" AND country LIKE "United%")
// ORDER BY name ASC LIMIT 20 OFFSET 0
Add a pre-save hook to hash a password field and register a custom validator.
import { connect, model, start, close, Schema, addValidators } from './ottoman/source';
import { createHash } from 'crypto';
addValidators({
strongPassword: (value: string) => {
if (value.length < 8) throw new Error('Password must be at least 8 characters');
},
});
const accountSchema = new Schema({
username: { type: String, required: true },
password: { type: String, validator: 'strongPassword' },
});
accountSchema.pre('save', async function (this: any) {
if (this.password) {
this.password = createHash('sha256').update(this.password).digest('hex');
}
});
async function run() {
await connect(`couchbase://localhost/default@admin:password`);
const Account = model('Account', accountSchema);
await start();
const acc = new Account({ username: 'alice', password: 'securePass123' });
await acc.save();
console.log('Hashed password stored:', acc.password);
await close();
}
run().catch(console.error);
index.ts - Barrel file; the only import path consumers need.couchbase.ts - Thin re-export of Couchbase SDK symbols used internally; do not import directly.exceptions/exceptions.ts - Base OttomanError and typed error subclasses thrown by the ODM.exceptions/ottoman-errors.ts - Mapping of error codes to human-readable messages.handler/find/ - find, findById, FindOptions, and FindByIdOptions implementations.handler/store.ts - Core upsert/insert logic invoked by document.save().handler/remove.ts - Single-document removal handler.handler/remove-many.ts - Bulk removal returning IManyQueryResponse.handler/update_many.ts - Bulk update with UpdateManyOptions.handler/create-many.ts - Bulk insert helper.handler/utils.ts - Shared handler utilities (key building, CAS handling).handler/types.ts - Shared handler TypeScript interfaces.model/model.ts - Model class: static finders, save, remove, validate, population.model/document.ts - Document base class extended by every model instance.model/create-model.ts - Factory wiring schema + Ottoman instance into a model constructor.model/model.types.ts - saveOptions, ModelTypes enums/interfaces.model/hooks/exec-hooks.ts - Runs pre/post hook chains.model/index/n1ql/ - N1QL index creation and query generation.model/index/refdoc/ - Reference-document index build helpers.model/index/view/ - Couchbase View index helpers and query builder.model/utils/ - Utilities: array diff, ref-key extraction, store/remove lifecycle orchestration.ottoman/ottoman.ts - Ottoman class and module-level singleton helpers (connect, model, start, close, getDefaultInstance).plugins/global-plugin-handler.ts - registerGlobalPlugin implementation.plugins/global-plugin-handler-error.ts - Error boundary for plugin execution.query/query.ts - Query fluent builder class.query/helpers/builders.ts - selectBuilder, buildSelectExpr, buildWhereClauseExpr, buildIndexExpr.query/helpers/dictionary.ts - AggDict, ResultExprDict, ReturnResultDict constant maps.query/interface/query.types.ts - All query-related TypeScript interfaces and union types.query/exceptions.ts - Query-specific exception classes.query/utils.ts - parseStringSelectExpr, escapeReservedWords.schema/schema.ts - Schema class definition.schema/types/ - Built-in types: StringType, NumberType, BooleanType, DateType, ArrayType, EmbedType, ReferenceType, MixedType, CoreType.schema/helpers/ - validate, applyDefaultValue, buildFields, registerType, addValidators.schema/errors/ - ValidationError, BuildSchemaError.schema/interfaces/ - IOttomanType, ValidatorOption interfaces.apt install build-essential / xcode-select --install) so node-gyp can compile from source.start() not called before queries - N1QL indexes are not ensured until start() resolves; calling find before it causes index not found errors. Always await start() after all models are defined.couchbase://host/bucketName@user:password. Omitting the bucket segment causes a silent connection to the wrong bucket.scopeName/collectionName options on older servers throws runtime errors."type": "module", set "moduleResolution": "node16" and use .js extensions in relative imports, or keep Ottoman in a CJS subpackage.connect twice creates a second instance. Use getDefaultInstance() to retrieve the existing one rather than reconnecting.I am integrating the Ottoman ODM source (located at `src/ottoman/source/`) into
my Node.js TypeScript project. The upstream package is `user@example.com`.
I have already read `USAGE.md` which documents the real exports and working examples.
Please help me do the following step-by-step:
1. Verify my `tsconfig.json` has the correct settings for Ottoman (moduleResolution, esModuleInterop, paths alias).
2. Create a `db.ts` connection module that reads COUCHBASE_URL, COUCHBASE_BUCKET, COUCHBASE_USER, COUCHBASE_PASS from environment variables and exports a `connectDB` function using `connect` and `start` from `src/ottoman/source/index.ts`.
3. Define a typed model for [describe your entity] using the `Schema` class and `model` function from the same source.
4. Add a repository layer with `findById`, `find` with pagination (`FindOptions` / `limit` / `offset`), `save`, and `removeById`.
5. Wire the repository into my existing Express route handlers.
6. Show me how to use the `Query` builder for any complex aggregation I describe.
Only use exports that appear in `src/ottoman/source/index.ts`. Do not install the `ottoman` npm package — I am using the embedded source directly.
Ottoman is released under the Apache License 2.0. See source/ for the full source or visit the upstream repository. Upstream npm package: user@example.com. Copyright 2021 Couchbase Inc.
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
完整安装指南与集成提示词将在购买后解锁。
Automation, Utilities & Developer Tools
免费