由 Esme R. 出售

Neogma is a Neo4j Object Graph Mapper for Node.js that provides type-safe models, a flexible query builder, automatic relationship management, and eager loading to eliminate N+1 queries.
Neogma is a TypeScript-first Object Graph Mapper (OGM) for Neo4j that provides type-safe models, a programmatic query builder, and automatic relationship management. It targets backend Node.js services that need structured, validated access to a Neo4j graph database without writing raw Cypher for every operation.
BindParam/ - Manages named Cypher query parameters, preventing injection and name collisionsErrors/ - Typed error classes: NeogmaError, NeogmaConnectivityError, NeogmaConstraintError, NeogmaNotFoundError, NeogmaInstanceValidationErrorLiteral/ - Wraps raw Cypher strings so they pass through query builders unescapedModelFactory/ - Core OGM: defines models, schemas, relationships, and all CRUD operationsQueryBuilder/ - Programmatic, chainable Cypher query builderQueryRunner/ - Low-level query execution layer wrapping the Neo4j driver sessionSessions/ - Session and transaction management helpersWhere/ - Type-safe WHERE clause construction for Cypher queriesutils/ - Internal utility functions shared across modulesNeogma.ts - Root class: initialises the Neo4j driver connectionindex.ts - Barrel export for the entire packagenpm install neo4j-driver revalidator clone @types/revalidator
npm install --save-dev typescript @types/node
No native build steps, pod installs, or binary linking required. This is a pure Node.js package.
Copy source: place the source/ directory into your project, for example at src/lib/neogma/.
Update tsconfig.json to ensure source/ is included and decorators are not required:
{
"compilerOptions": {
"target": "ES2019",
"module": "commonjs",
"moduleResolution": "node",
"strict": true,
"esModuleInterop": true,
"outDir": "dist",
"rootDir": "src"
},
"include": ["src/**/*"]
}
启动隔离沙箱并在服务器端直接运行 — 无需本地配置。
此版本的 Tetrees AI Review
This TypeScript cli / script 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 53a60008a3d56ca1…
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…
dotenvNEO4J_URL=bolt://localhost:7687
NEO4J_USERNAME=neo4j
NEO4J_PASSWORD=password
NEO4J_DATABASE=neo4j # optional, defaults to neo4j
// src/db.ts
import { Neogma } from './lib/neogma';
export const neogma = new Neogma({
url: process.env.NEO4J_URL!,
username: process.env.NEO4J_USERNAME!,
password: process.env.NEO4J_PASSWORD!,
});
neogma instance to ModelFactory.import { Neogma } from './lib/neogma';
const neogma = new Neogma(connectionConfig: {
url: string;
username: string;
password: string;
database?: string;
});
The root connection object. Instantiate once per process and share across models. It wraps the neo4j-driver Driver and exposes it for QueryRunner and session management.
import { ModelFactory } from './lib/neogma';
const Model = ModelFactory<Properties, RelatedNodes>(
config: {
label: string | string[];
schema: Record<keyof Properties, SchemaField>;
primaryKeyField: keyof Properties;
relationships?: RelationshipsI<RelatedNodes>;
statics?: Record<string, Function>;
methods?: Record<string, Function>;
},
neogma: Neogma
);
Creates a typed model class with static methods (createOne, createMany, findOne, findMany, updateMany, deleteMany, createRelationship, findRelationships) and instance methods (save, delete, findRelationships, getDataValues). Use this as the primary entry point for all node operations.
import { BindParam } from './lib/neogma';
const bp = new BindParam({ key: 'value' });
bp.add({ anotherKey: 123 });
const params = bp.get(); // { key: 'value', anotherKey: 123 }
Accumulates Cypher parameters across composed query fragments, deduplicated and safe. Pass the same BindParam instance to QueryBuilder and Where to share parameters across clauses.
import type { ModelRelatedNodesI, NeogmaInstance } from './lib/neogma';
NeogmaInstance<Properties, RelatedNodes> is the type of hydrated model instances returned from findOne/createOne. ModelRelatedNodesI types the relationship configuration inside model definitions. Import these for type annotations without runtime cost.
import { RESERVED_INSTANCE_PROPERTIES, RESERVED_RELATIONSHIP_ALIASES } from './lib/neogma';
Constants enumerating property names that Neogma reserves internally. Reference these when validating user-supplied schemas to avoid collisions.
Define a typed User model with schema validation and persist a node to Neo4j.
import { Neogma, ModelFactory } from './lib/neogma';
const neogma = new Neogma({
url: process.env.NEO4J_URL!,
username: process.env.NEO4J_USERNAME!,
password: process.env.NEO4J_PASSWORD!,
});
type UserProps = { id: string; name: string; email: string };
const Users = ModelFactory<UserProps, {}>({
label: 'User',
schema: {
id: { type: 'string', required: true },
name: { type: 'string', required: true },
email: { type: 'string', required: true },
},
primaryKeyField: 'id',
}, neogma);
async function run() {
const user = await Users.createOne({
id: crypto.randomUUID(),
name: 'Alice',
email: 'alice@example.com',
});
console.log(user.id, user.name);
user.name = 'Alicia';
await user.save(); // persists the change
}
run();
Use findOne and findMany with typed WHERE conditions and handle the nullable result.
import { Neogma, ModelFactory, NeogmaNotFoundError } from './lib/neogma';
// reuse Users model from previous scenario
async function findUser(email: string) {
const user = await Users.findOne({ where: { email } });
if (!user) {
throw new NeogmaNotFoundError(`No user with email ${email}`);
}
return user.getDataValues(); // plain object, no OGM metadata
}
async function listUsers() {
const users = await Users.findMany({ limit: 20 });
return users.map(u => u.getDataValues());
}
Define two models linked by a relationship, create them together, and load them with eager relationships.
import {
Neogma,
ModelFactory,
ModelRelatedNodesI,
NeogmaInstance,
} from './lib/neogma';
type OrderProps = { id: string; status: string };
const Orders = ModelFactory<OrderProps, {}>({
label: 'Order',
schema: {
id: { type: 'string', required: true },
status: { type: 'string', required: true },
},
primaryKeyField: 'id',
}, neogma);
type UserProps = { id: string; name: string };
type UserRelated = { Orders: ModelRelatedNodesI<typeof Orders, {}, 'PLACES'> };
const Users = ModelFactory<UserProps, UserRelated>({
label: 'User',
schema: {
id: { type: 'string', required: true },
name: { type: 'string', required: true },
},
primaryKeyField: 'id',
relationships: {
Orders: {
model: Orders,
direction: 'out',
name: 'PLACES',
},
},
}, neogma);
async function createUserWithOrder() {
await Users.createMany([
{
id: 'u1',
name: 'Bob',
Orders: {
attributes: [{ id: 'o1', status: 'pending' }],
},
},
]);
const usersWithOrders = await Users.findMany({
where: { id: 'u1' },
relationships: [{ alias: 'Orders', include: 'all' }],
});
console.log(usersWithOrders[0].Orders); // typed eager-loaded relationship data
}
Handle specific Neogma error types to return appropriate HTTP responses.
import {
NeogmaError,
NeogmaConstraintError,
NeogmaConnectivityError,
NeogmaInstanceValidationError,
} from './lib/neogma';
async function createSafe(data: unknown) {
try {
await Users.createOne(data as any);
} catch (err) {
if (err instanceof NeogmaConstraintError) {
return { status: 409, message: 'Duplicate key constraint violated' };
}
if (err instanceof NeogmaInstanceValidationError) {
return { status: 422, message: 'Schema validation failed' };
}
if (err instanceof NeogmaConnectivityError) {
return { status: 503, message: 'Database unreachable' };
}
if (err instanceof NeogmaError) {
return { status: 500, message: err.message };
}
throw err;
}
}
index.ts - Master barrel; re-exports every sub-module including neo4jDriver as a named namespace.Neogma.ts - Connection bootstrapper; wraps neo4j-driver Driver creation and exposes it.BindParam/BindParam.ts - Parameter accumulator for safe Cypher parameterisation.Errors/NeogmaError.ts - Base error class all Neogma errors extend.Errors/NeogmaConnectivityError.ts - Thrown when the driver cannot reach Neo4j.Errors/NeogmaConstraintError.ts - Thrown on unique-constraint violations from Neo4j.Errors/NeogmaNotFoundError.ts - Utility error for missing node results.Errors/NeogmaInstanceValidationError.ts - Thrown when a model instance fails revalidator schema checks.Literal/Literal.ts - Wraps a raw Cypher string that must not be escaped or parameterised.ModelFactory/ModelFactory.ts - Assembles the full model class with statics, methods, and relationship config.ModelFactory/model.types.ts - Core public types: NeogmaModel, NeogmaInstance, RelationshipsI, etc.ModelFactory/relationship.types.ts - Types for relationship configuration objects.ModelFactory/shared.types.ts - Shared utility types used across ModelFactory sub-modules.ModelFactory/findMany/ - findMany static, eager loading query builder, and hydration logic.ModelFactory/findOne/ - Thin wrapper around findMany returning first result.ModelFactory/createOne/ - Single-node creation with relationship creation support.ModelFactory/createMany/ - Batch node creation using a single Cypher statement.ModelFactory/createRelationship/ - Static to create a relationship between two existing nodes.ModelFactory/delete/ - Instance and static deletion methods.ModelFactory/deleteRelationships/ - Static to delete specific relationships between nodes.ModelFactory/findRelationships/ - Static and instance methods to query relationships.ModelFactory/update/ - Bulk property update static.ModelFactory/updateRelationship/ - Updates properties on relationship records.ModelFactory/save/ - Instance save() method: upserts dirty properties.ModelFactory/getDataValues/ - Strips OGM metadata, returns plain property object.ModelFactory/validate/ - Triggers revalidator schema validation on an instance.ModelFactory/validation/ - Schema validation helpers and reserved-name constants.ModelFactory/labelConfig/ - Normalises single/multi-label configuration.ModelFactory/relationshipConfig/ - Parses and validates relationship definition objects.ModelFactory/utils/ - Internal helpers shared by ModelFactory sub-modules.ModelFactory/testHelpers.ts - Exported test utilities for integration test setup.QueryBuilder/ - Chainable builder that emits { query, parameters } pairs.QueryRunner/ - Executes queries against a driver session; handles result mapping.Sessions/ - Helpers for obtaining sessions and running transactions.Where/ - Builds typed Cypher WHERE clauses from plain JS filter objects.utils/ - Generic utilities (object helpers, type guards) used internally.NeogmaConnectivityError on startup: Neo4j may not be ready before Node.js connects; wrap new Neogma(...) in a retry loop or wait for the healthcheck endpoint.revalidator only throws when you call instance.validate() explicitly or when saving; always define required: true for mandatory fields so creation fails fast.relationships[].alias in findMany must exactly match the key used in the model's relationships config object.neo4j-driver version mismatch: Neogma 1.16.x pins to a specific neo4j-driver major; installing a mismatched version causes session API errors at runtime. Pin to the version in source/ peer requirements."type": "module" in package.json, import neo4j-driver via the neo4jDriver namespace re-exported from index.ts or configure esModuleInterop: true in tsconfig.json._fields, labels, or anything in RESERVED_INSTANCE_PROPERTIES will conflict with internal OGM properties; rename them in your schema and use Cypher aliases if needed.I have copied the Neogma OGM source into `src/lib/neogma/` in my Node.js
TypeScript project. The integration guide is in `USAGE.md`. The upstream
package is `user@example.com`.
Please help me integrate Neogma step by step:
1. Read `USAGE.md` for the full API, imports, and working examples.
2. All imports must come from `./lib/neogma` (or a relative path to
`src/lib/neogma/index.ts`). Do not import from the npm package directly.
3. Create a `src/db.ts` that initialises `Neogma` using environment variables
NEO4J_URL, NEO4J_USERNAME, NEO4J_PASSWORD.
4. Define a `ModelFactory` model for [DESCRIBE YOUR NODE TYPE AND PROPERTIES].
5. Add relationships to [DESCRIBE RELATED MODELS] with direction [in/out] and
relationship name [REL_NAME].
6. Wire the model into [my Express router / service class / wherever].
7. Add typed error handling using `NeogmaConstraintError`,
`NeogmaNotFoundError`, and `NeogmaInstanceValidationError`.
8. Show me `findMany` with eager relationship loading for [ALIAS].
Only use symbols and method signatures documented in `USAGE.md`. Do not invent
new APIs.
Neogma is released under the MIT License. See the upstream repository for the full license text. Source: neogma on npm / themetalfleece/neogma on GitHub. This AVCP block vendors user@example.com unmodified for use as a local source dependency.
This product’s unique contribution is clean room implementation of valuable code block into AVCP compatible standard.
完整安装指南与集成提示词将在购买后解锁。
Automation, Utilities & Developer Tools
免费