SDK de JavaScript
@namidb/cloud es el cliente oficial de JavaScript y TypeScript. Ejecuta
Cypher sobre la API HTTP y envuelve la
API de gestión. No tiene dependencias en
tiempo de ejecución y solo necesita el fetch global, así que funciona en
Node 18+, Deno, Bun, runtimes edge y navegadores. Apache-2.0.
npm install @namidb/cloudInicio rápido
import { NamiDB } from '@namidb/cloud';
const db = new NamiDB(); // reads NAMIDB_API_KEY (and NAMIDB_URL, default https://db.namidb.com)
await db.query('movies', 'CREATE (:Movie {id: $id, title: $title})', { id: 'm1', title: 'Heat' });
const { rows } = await db.query<{ title: string }>( 'movies', 'MATCH (m:Movie) RETURN m.title AS title ORDER BY title LIMIT $n', { n: 10 },);
const movies = db.database('movies'); // bind one databaseconst schema = await movies.schema();new NamiDB(options?)
| Opción | Por defecto | |
|---|---|---|
apiKey | process.env.NAMIDB_API_KEY | Obligatoria; si falta, el constructor lanza missing_api_key |
url | process.env.NAMIDB_URL ?? https://db.namidb.com | |
timeoutMs | 90000 | Por intento. Cubre el timeout de consulta del plan más largo (60 s) más un arranque en frío |
maxRetries | 2 | Reintentos después del primer intento |
fetch | globalThis.fetch | Tu propia implementación de fetch |
Métodos
db.query<T>(database, cypher, params?, options?)
Resuelve a:
{ columns: string[]; rows: T[]; // one object per row, keyed by column writeOutcome?: { nodesCreated, edgesCreated, nodesDeleted, edgesDeleted, propertiesSet }; requestId: string | null; // quote it to support engineMs: number | null; // time spent in the engine}options: idempotent (consulta Reintentos), timeoutMs y
signal (un AbortSignal que cancela la petición y cualquier reintento
pendiente).
Los valores usan la codificación JSON del motor: un nodo es
{ _kind: 'node', id, label, labels, properties }, una relación
{ _kind: 'rel', edge_type, src, dst, properties }, los datetimes son strings
RFC 3339, los bytes base64 y los vectores arrays de números. Los enteros llegan
como números de JavaScript: usa strings para identificadores mayores que
Number.MAX_SAFE_INTEGER. Los parámetros deben ser serializables a JSON (sin
BigInt).
db.schema(database, options?)
{ constraints, indexes, labels, relationshipTypes, requestId }; cada
constraint e índice es { name, type, entityType, labelsOrTypes, properties }.
db.databases(options?)
Las bases de datos a las que llega la key: [{ name, status }].
db.runningQueries(database, options?) y db.cancelQuery(database, id, options?)
runningQueries resuelve a las sentencias que se están ejecutando en la base
de datos en este momento, de la más larga a la más corta:
[{ id, protocol, statement, elapsedMs }]. cancelQuery detiene una de ellas
en su siguiente punto de verificación, y su cliente recibe un error
cancelled. Ambas necesitan una key de lectura y escritura (read_only_key
si no), porque el texto de las sentencias incluye sus literales. Cancelar una
sentencia que ya no se está ejecutando lanza query_not_found.
import { NamiDB, NamiDBError } from '@namidb/cloud';
for (const q of await db.runningQueries('movies')) { if (q.elapsedMs > 60_000) { await db.cancelQuery('movies', q.id).catch((err) => { if (!(err instanceof NamiDBError && err.code === 'query_not_found')) throw err; }); }}Listar se reintenta como una lectura y nunca despierta una base de datos dormida (en ese caso no tiene nada en ejecución). Una cancelación se reintenta solo cuando NamiDB la rechazó antes de que pudiera tener efecto. Ninguna de las dos cuenta como petición.
db.database(name)
Un handle con query, schema, runningQueries, cancelQuery,
bulkWrite, importNodes e importRelationships ligados a esa base de
datos.
Importación masiva
await db.importNodes('movies', people, { label: 'Person', key: 'id', // MERGE on id; other fields become properties onProgress: (p) => console.log(p.rowsDone, p.rowsTotal),});
const res = await db.importRelationships('movies', [{ from: 1, to: 2, since: 2020 }], { type: 'KNOWS', from: { label: 'Person', key: 'id' }, to: { label: 'Person', key: 'id' },}); // res.linked counts rows whose two ends exist
await db.bulkWrite('movies', 'UNWIND $rows AS row MERGE (m:Movie {title: row.title})', titles, { idempotent: true });Los lotes se cortan en batchRows (1,000 por defecto) y batchBytes (1 MiB por
defecto), esperan ante rate_limited y engine_starting lo que indique
Retry-After (maxRateLimitRetries, 30 por defecto) y se dividen a la mitad
ante payload_too_large. Los lotes con MERGE se reintentan como las
lecturas; un lote con CREATE nunca se reenvía después de un fallo ambiguo. Un
fallo lanza un NamiDBError que indica cuántas filas entraron antes.
Errores
Todo fallo rechaza con un NamiDBError: code, status (0 cuando no llegó
ninguna respuesta), message, requestId, retryAfter (segundos o null), y
neo4jCode / gqlStatus cuando el motor los informó.
import { NamiDB, NamiDBError } from '@namidb/cloud';
try { await db.query('movies', 'CREATE (:Movie {id: "m1"})');} catch (err) { if (err instanceof NamiDBError && err.code === 'read_only_key') { // this key can only read } else if (err instanceof NamiDBError && err.code === 'plan_limit') { // allowance used up: upgrade, or wait err.retryAfter seconds } else { throw err; }}Todos los códigos: Errores. Códigos del lado del
cliente: request_timeout, connection_error, invalid_response,
invalid_argument, missing_api_key, http_error.
Reintentos
Hasta maxRetries veces, esperando lo que indique Retry-After cuando el
servidor lo envía (si es más de 60 s, se informa en lugar de esperar), y si no,
con backoff exponencial con jitter de 0.5 s a 8 s.
Las escrituras nunca se reintentan una vez que pudieron haber llegado al
motor. Una consulta cuenta como escritura cuando contiene una cláusula de
escritura (CREATE, MERGE, SET, DELETE, REMOVE, DROP, CALL, …). Las
escrituras sí se reintentan cuando NamiDB las rechazó antes de que el motor las
viera (engine_starting, rate_limited, control_plane_unavailable) o cuando
la conexión nunca se estableció. Puedes cambiar esta verificación en cada
llamada:
await db.query('movies', 'MERGE (:Movie {id: $id})', { id: 'm1' }, { idempotent: true }); // safe to repeatawait db.query('movies', 'MATCH (n) RETURN n', {}, { idempotent: false }); // never repeatschema() y databases() siempre se reintentan.
API de gestión
ManagementClient usa un token de gestión (nmdb_mgmt_…) contra
https://app.namidb.com/api/v1.
import { ManagementClient } from '@namidb/cloud';
const mgmt = new ManagementClient(); // reads NAMIDB_MANAGEMENT_TOKEN (and NAMIDB_MANAGEMENT_URL)
const db = await mgmt.databases.create('movies');const key = await mgmt.apiKeys.create({ name: 'movies-app', role: 'read-only', databases: ['movies'] });console.log(key.token); // the full API key, returned this once
const backup = await mgmt.backups.create('movies');await mgmt.restores.create({ backupId: backup.id, databaseName: 'movies-copy' });await mgmt.clones.create('movies', { name: 'movies-staging', source: 'fresh_snapshot' });// The database as it was 24 hours ago (exact inside the plan's restore-point window).const pit = await mgmt.restores.pointInTime('movies', { at: new Date(Date.now() - 86_400_000), databaseName: 'movies-yesterday' });// poll mgmt.clones.get(pit.id) until 'succeeded'; then pit.recoveryPoint and pit.recoverySource say what it holds
// A short-lived token for a CI job (needs the admin scope; never broader or longer-lived than this one).const ci = await mgmt.managementTokens.create({ name: 'ci', scope: 'write', expiresAt: new Date(Date.now() + 3_600_000) });console.log(ci.token); // shown this once
const exp = await mgmt.exports.create('movies'); // poll mgmt.exports.get(exp.id) until 'succeeded'const cypher = await mgmt.exports.download(exp.id, 'import.cypher');
await mgmt.ipAllowlist.add({ cidr: '203.0.113.0/24', label: 'office' });for await (const d of mgmt.databases.listAll()) console.log(d.name, d.status, d.endpoints.http);| Recurso | Métodos |
|---|---|
mgmt.organization(), mgmt.usage() | La organización del token; el uso de este periodo |
mgmt.databases | list, listAll, create(name), get(name), delete(name) |
mgmt.backups | list(database), create(database), get(id) |
mgmt.restores | create({ backupId, databaseName }), pointInTime(database, { at, databaseName }) (un clon point_in_time), get(id) |
mgmt.clones | create(database, { name, source, at }) (latest_backup, fresh_snapshot, point_in_time), get(id) |
mgmt.exports | list(database), create(database), get(id), download(id, file) |
mgmt.ipAllowlist | list({ apiKeyId }), add({ cidr, label, apiKeyId }), remove(id) |
mgmt.apiKeys | list, listAll, create({ name, role, databases, expiresAt }), get, rotate(id, { overlapDays }), revoke(id) |
mgmt.managementTokens | list, listAll, create({ name, scope, expiresAt }) (el secreto está en token, una sola vez), get(id), revoke(id); scope admin |
mgmt.members | list, listAll, remove(userId) |
mgmt.invitations | list, create({ email, role }), revoke(id) |
mgmt.support | list, listAll, create({ subject, body, category, severity, database }), get(number), reply(number, body) |
Opciones: token, url, timeoutMs (30,000 por defecto), maxRetries (2 por
defecto), fetch. Los resultados usan camelCase (readOnly, createdAt,
recoverySource, sourceCreatedAt, mintedBy).
list devuelve una página { data, nextCursor } (limit 1–100, cursor);
listAll recorre todas las páginas. rate_limited,
control_plane_unavailable, 502–504 y los errores de conexión se reintentan
con backoff. Cada creación envía un Idempotency-Key (uno nuevo, o el
idempotencyKey que pases) y lo reutiliza en los reintentos.
Navegadores y runtimes edge
El cliente funciona donde exista fetch, pero una key en un navegador es
visible para todos los visitantes. Mantén las keys en un servidor o en una
función edge; cuando una key tenga que llegar a los usuarios, usa una key de
solo lectura con alcance sobre una sola base de datos. En los navegadores el
cliente no define User-Agent.
Changelog
Las notas de versión están en el CHANGELOG.md del paquete en npm.