Datos y almacenamiento
## g.store.* — almacenamiento persistente
Sección titulada «## g.store.* — almacenamiento persistente»Almacenamiento de documentos limitado al espacio de trabajo y respaldado por LiteDB. Requiere un espacio de trabajo abierto.
| Método | Firma | Async | Descripción |
|---|---|---|---|
put | (collection, key, data) | No | Almacena un documento |
get | (collection, key) → StoreDoc | null | No | Recupera un documento |
list | (collection, options?) → StoreDoc[] | No | Lista documentos de una colección |
search | (collection, query, options?) → StoreDoc[] | No | Busca texto dentro de una colección |
delete | (collection, key) → boolean | No | Elimina un documento |
count | (collection) → number | No | Cuenta documentos |
clear | (collection) | No | Elimina todos los documentos de una colección |
collections | () → string[] | No | Lista todos los nombres de colección |
StoreDoc:
{ key: string data: any createdAt: string // ISO 8601 updatedAt: string // ISO 8601}StoreListOptions:
{ limit?: number // default: 100 offset?: number // default: 0 sort?: string // "key", "createdAt", "updatedAt" (default) order?: string // "asc" or "desc" (default)}Ejemplo
Sección titulada «Ejemplo»async function main() { // Store data g.store.put("products", "item-1", { name: "Widget", price: 9.99, inStock: true });
// Retrieve it const doc = g.store.get("products", "item-1"); if (doc) g.log("Found: " + doc.data.name);
// Search const results = g.store.search("products", "Widget"); g.log("Matches: " + results.length);}## g.queue.* — cola de trabajo
Sección titulada «## g.queue.* — cola de trabajo»Cola persistente limitada al espacio de trabajo, con niveles de prioridad y soporte de cola de rechazos. Requiere un espacio de trabajo abierto.
| Método | Firma | Async | Descripción |
|---|---|---|---|
enqueue | (name, data, options?) | No | Añade un elemento a una cola |
dequeue | (name) → QueueItem | null | No | Toma el siguiente elemento |
commit | (checkoutId) | No | Marca un elemento tomado como completado |
abort | (checkoutId, error?) → boolean | No | Devuelve un elemento a la cola o lo mueve a rechazos si superó los reintentos |
peek | (name) → QueueItem | null | No | Ve el siguiente elemento sin tomarlo |
count | (name) → number | No | Cuenta elementos pendientes |
clear | (name) | No | Elimina todos los elementos de una cola |
list | (name, options?) → QueueItem[] | No | Lista elementos pendientes |
queues | () → string[] | No | Lista todos los nombres de cola |
deadLetter | (name, options?) → DeadLetterItem[] | No | Lista elementos en la cola de rechazos |
retry | (name, deadLetterId) | No | Vuelve a poner en cola un elemento rechazado |
waitForItem | (name, options?) → Promise<QueueItem | null> | Sí | Bloquea hasta que haya un elemento disponible |
QueueEnqueueOptions:
{ priority?: number // 0=low, 1=normal (default), 2=high maxRetries?: number // default: 3}QueueItem:
{ id: number data: any priority: number attempts: number maxRetries: number enqueuedAt: string lastAttemptAt?: string lastError?: string}Ejemplo
Sección titulada «Ejemplo»async function main() { // Enqueue work items g.queue.enqueue("urls", { url: "https://example.com/page1" }); g.queue.enqueue("urls", { url: "https://example.com/page2" }, { priority: 2 });
// Process items const item = g.queue.dequeue("urls"); if (!item) return g.log("Queue empty");
await g.nav.navigateToUrl(item.data.url); const html = await g.page.getDom();
// Mark complete g.queue.commit(item.id);}## g.search.* — búsqueda de texto completo
Sección titulada «## g.search.* — búsqueda de texto completo»Índice Lucene.NET limitado al espacio de trabajo. Admite operadores booleanos, comodines, coincidencia aproximada y consultas por campo. Requiere un espacio de trabajo abierto.
| Método | Firma | Async | Descripción |
|---|---|---|---|
index | (fields) | No | Indexa un documento; debe incluir _key y _collection |
query | (queryString, options?) → SearchResult[] | No | Busca en el índice con sintaxis Lucene |
delete | (collection, key) | No | Elimina un documento del índice |
deleteByCollection | (collection) → number | No | Elimina todos los documentos de una colección |
count | (collection?) → number | No | Cuenta documentos indexados |
clear | () | No | Limpia todo el índice |
SearchResult:
{ key: string collection: string score: number // Lucene relevance score fields: Record<string, string>}Ejemplo
Sección titulada «Ejemplo»async function main() { // Index documents g.search.index({ _key: "article-1", _collection: "articles", title: "Getting Started with Guida", body: "Guida is a scriptable browser..." });
// Query with Lucene syntax const results = g.search.query("scriptable browser", { collection: "articles" }); for (const r of results) { g.log(r.fields.title + " (score: " + r.score + ")"); }}## g.s3.* — almacenamiento de objetos compatible con S3
Sección titulada «## g.s3.* — almacenamiento de objetos compatible con S3»Almacenamiento compatible con S3 mediante MinIO SDK. Funciona con AWS S3, MinIO y cualquier servicio compatible con S3. El parámetro conn es el nombre de una credencial que contiene la cadena de conexión. Bloqueado para scripts originados por MCP.
| Método | Firma | Async | Descripción |
|---|---|---|---|
listBuckets | (conn) → Promise<S3BucketInfo[]> | Sí | Lista todos los buckets accesibles |
bucketExists | (conn, bucket) → Promise<boolean> | Sí | Comprueba si existe un bucket |
listObjects | (conn, bucket, options?) → Promise<S3ObjectInfo[]> | Sí | Lista objetos de un bucket |
getObjectText | (conn, bucket, key) → Promise<string> | Sí | Descarga un objeto como texto UTF-8 |
getObject | (conn, bucket, key, localPath) → Promise | Sí | Descarga un objeto a un archivo local |
putObjectText | (conn, bucket, key, content, contentType?) → Promise | Sí | Sube texto como objeto |
putObject | (conn, bucket, key, localPath, contentType?) → Promise | Sí | Sube un archivo local como objeto |
deleteObject | (conn, bucket, key) → Promise | Sí | Elimina un objeto |
objectExists | (conn, bucket, key) → Promise<boolean> | Sí | Comprueba si existe un objeto |
createBucket | (conn, bucket, region?) → Promise | Sí | Crea un bucket nuevo |
copyObject | (conn, srcBucket, srcKey, dstBucket, dstKey) → Promise | Sí | Copia del lado servidor, sin pasar datos por el cliente |
getPresignedUrl | (conn, bucket, key, options?) → Promise<string> | Sí | Genera una URL prefirmada con caducidad |
S3ListOptions:
{ prefix?: string // filter objects by key prefix maxKeys?: number // max objects to return (default: 1000)}S3BucketInfo:
{ name: string creationDate: string // ISO 8601}S3ObjectInfo:
{ key: string // object key (path) size: number // size in bytes lastModified: string // ISO 8601 etag: string // entity tag (hash)}S3PresignedUrlOptions:
{ method?: string // "GET" (download, default) or "PUT" (upload) expiry?: number // URL expiry in seconds (default: 3600)}Ejemplo
Sección titulada «Ejemplo»async function main() { // List CSV files in a bucket const files = await g.s3.listObjects("my-s3", "data-bucket", { prefix: "exports/" }); g.log("Found " + files.length + " objects");
// Upload scraped data await g.s3.putObjectText( "my-s3", "data-bucket", "exports/results.json", JSON.stringify({ items: [1, 2, 3] }), "application/json" );
// Generate a shareable link const url = await g.s3.getPresignedUrl("my-s3", "data-bucket", "exports/results.json", { expiry: 86400 // 24 hours }); g.log("Download link: " + url);}## g.mongodb.* — MongoDB
Sección titulada «## g.mongodb.* — MongoDB»Operaciones MongoDB mediante MongoDB.Driver. El parámetro conn es el nombre de una credencial que contiene la cadena de conexión. Usa pooling automático de conexiones. Bloqueado para scripts originados por MCP.
| Método | Firma | Async | Descripción |
|---|---|---|---|
find | (conn, db, collection, filter?, options?) → Promise<object[]> | Sí | Busca documentos que coinciden con un filtro |
findOne | (conn, db, collection, filter?) → Promise<object | null> | Sí | Busca el primer documento coincidente |
insertOne | (conn, db, collection, document) → Promise<MongoInsertResult> | Sí | Inserta un documento |
insertMany | (conn, db, collection, documents) → Promise<MongoInsertManyResult> | Sí | Inserta varios documentos |
updateOne | (conn, db, collection, filter, update) → Promise<MongoUpdateResult> | Sí | Actualiza el primer documento coincidente |
updateMany | (conn, db, collection, filter, update) → Promise<MongoUpdateResult> | Sí | Actualiza todos los documentos coincidentes |
deleteOne | (conn, db, collection, filter) → Promise<MongoDeleteResult> | Sí | Elimina el primer documento coincidente |
deleteMany | (conn, db, collection, filter) → Promise<MongoDeleteResult> | Sí | Elimina todos los documentos coincidentes |
replaceOne | (conn, db, collection, filter, replacement) → Promise<MongoUpdateResult> | Sí | Reemplaza el primer documento coincidente |
countDocuments | (conn, db, collection, filter?) → Promise<number> | Sí | Cuenta documentos coincidentes |
listDatabases | (conn) → Promise<string[]> | Sí | Lista todos los nombres de base de datos |
listCollections | (conn, db) → Promise<string[]> | Sí | Lista nombres de colección en una base |
aggregate | (conn, db, collection, pipeline) → Promise<object[]> | Sí | Ejecuta una canalización de agregación |
createIndex | (conn, db, collection, keys, options?) → Promise<string> | Sí | Crea un índice y devuelve su nombre |
dropCollection | (conn, db, collection) → Promise | Sí | Elimina una colección |
distinct | (conn, db, collection, fieldName, filter?) → Promise<any[]> | Sí | Obtiene valores distintos de un campo |
bulkWrite | (conn, db, collection, operations) → Promise<MongoBulkWriteResult> | Sí | Ejecuta varias operaciones de escritura por lotes |
MongoFindOptions:
{ sort?: object // e.g., { name: 1, age: -1 } limit?: number skip?: number projection?: object // e.g., { name: 1, _id: 0 }}MongoInsertResult:
{ insertedId: string // the _id of the inserted document}MongoInsertManyResult:
{ insertedCount: number insertedIds: string[]}MongoUpdateResult:
{ matchedCount: number modifiedCount: number}MongoDeleteResult:
{ deletedCount: number}MongoIndexOptions:
{ unique?: boolean // enforce uniqueness name?: string // custom index name}MongoBulkOperation:
{ type: string // "insertOne", "updateOne", "updateMany", // "deleteOne", "deleteMany", "replaceOne" filter?: object // for update/delete/replace document?: object // for insertOne update?: object // for updateOne/updateMany replacement?: object // for replaceOne}MongoBulkWriteResult:
{ insertedCount: number matchedCount: number modifiedCount: number deletedCount: number}Ejemplo
Sección titulada «Ejemplo»async function main() { const conn = "my-mongo"; // secret name with connection string
// Insert a document const result = await g.mongodb.insertOne(conn, "scraping", "products", { name: "Widget", price: 9.99, category: "tools" }); g.log("Inserted: " + result.insertedId);
// Find with filter and sort const docs = await g.mongodb.find(conn, "scraping", "products", { price: { $lt: 20 } }, { sort: { price: 1 }, limit: 10 } ); g.log("Found " + docs.length + " cheap products");
// Aggregation pipeline const stats = await g.mongodb.aggregate(conn, "scraping", "products", [ { $group: { _id: "$category", avgPrice: { $avg: "$price" }, count: { $sum: 1 } } }, { $sort: { count: -1 } } ]); for (const s of stats) { g.log(s._id + ": " + s.count + " items, avg $" + s.avgPrice.toFixed(2)); }}## g.postgres.* — PostgreSQL
Sección titulada «## g.postgres.* — PostgreSQL»Operaciones PostgreSQL mediante Npgsql. Usa parámetros posicionales $1, $2, ...; nunca interpole valores dentro de cadenas SQL. El parámetro conn es el nombre de una credencial que contiene la cadena de conexión. Usa pooling automático. Bloqueado para scripts originados por MCP.
| Método | Firma | Async | Descripción |
|---|---|---|---|
query | (conn, sql, params?) → Promise<object[]> | Sí | SELECT que devuelve todas las filas |
queryOne | (conn, sql, params?) → Promise<object | null> | Sí | SELECT que devuelve la primera fila |
execute | (conn, sql, params?) → Promise<PgExecuteResult> | Sí | INSERT/UPDATE/DELETE |
scalar | (conn, sql, params?) → Promise<any> | Sí | Devuelve la primera columna de la primera fila |
transaction | (conn, callback) → Promise<any> | Sí | Ejecuta el callback dentro de una transacción; solo JS |
executeBatch | (conn, statements) → Promise<PgBatchResult> | Sí | Varias sentencias en una única transacción |
copyFrom | (conn, table, rows, options?) → Promise<PgCopyResult> | Sí | Inserción por lotes mediante protocolo COPY |
copyTo | (conn, query, options?) → Promise<string[][]> | Sí | Exportación por lotes mediante protocolo COPY |
listDatabases | (conn) → Promise<string[]> | Sí | Lista nombres de bases no plantilla |
listSchemas | (conn, options?) → Promise<string[]> | Sí | Lista nombres de esquema |
listTables | (conn, schema?) → Promise<PgTableInfo[]> | Sí | Lista tablas y vistas con conteos de filas |
describeTable | (conn, table, schema?) → Promise<PgColumnInfo[]> | Sí | Metadatos de columnas: tipos, nulabilidad, valores por defecto y PK |
listIndexes | (conn, table, schema?) → Promise<PgIndexInfo[]> | Sí | Metadatos de índices con definiciones |
listConstraints | (conn, table, schema?) → Promise<PgConstraintInfo[]> | Sí | Metadatos de restricciones: PK, FK, UNIQUE, CHECK |
PgExecuteResult:
{ rowsAffected: number}PgTableInfo:
{ name: string schema: string type: string // "table" or "view" estimatedRows: number // from pg_class.reltuples}PgColumnInfo:
{ name: string type: string // e.g., "integer", "character varying", "timestamp with time zone" nullable: boolean defaultValue: string | null isPrimaryKey: boolean maxLength: number | null // for string types}PgIndexInfo:
{ name: string columns: string[] isUnique: boolean isPrimary: boolean definition: string // full CREATE INDEX statement}PgConstraintInfo:
{ name: string type: string // "PRIMARY KEY", "FOREIGN KEY", "UNIQUE", "CHECK" columns: string // comma-separated column names definition: string // constraint definition}PgBatchStatement:
{ sql: string // SQL with $1, $2, ... positional parameters params?: any[] // parameter values}PgBatchResult:
{ results: PgExecuteResult[] // per-statement rowsAffected counts}PgTransactionProxy — se pasa al callback de transaction:
{ query: (sql, params?) => Promise<object[]> queryOne: (sql, params?) => Promise<object | null> execute: (sql, params?) => Promise<PgExecuteResult> scalar: (sql, params?) => Promise<any>}PgCopyFromOptions:
{ columns?: string[] // column names to map row values to (in order) schema?: string // default: "public"}PgCopyToOptions:
{ schema?: string // default: "public" (only for table names, not SQL queries)}PgCopyResult:
{ rowsCopied: number}PgSchemaOptions:
{ includeSystem?: boolean // include pg_* and information_schema (default: false)}Ejemplo
Sección titulada «Ejemplo»async function main() { const conn = "my-postgres"; // secret name with connection string
try { // Query with parameters const rows = await g.postgres.query(conn, "SELECT id, name, price FROM products WHERE price < $1 ORDER BY price", [20.00] ); g.log("Found " + rows.length + " products");
// Transaction with callback const result = await g.postgres.transaction(conn, async (tx) => { await tx.execute("INSERT INTO orders (product_id, qty) VALUES ($1, $2)", [42, 3]); await tx.execute("UPDATE products SET stock = stock - $1 WHERE id = $2", [3, 42]); return await tx.scalar("SELECT count(*) FROM orders"); }); g.log("Total orders: " + result);
// Bulk insert via COPY (much faster than row-by-row INSERT) const copyResult = await g.postgres.copyFrom(conn, "products", [ ["Widget A", 9.99, 100], ["Widget B", 14.99, 50], ["Widget C", 24.99, 25] ], { columns: ["name", "price", "stock"] }); g.log("Imported " + copyResult.rowsCopied + " rows"); } catch (e) { g.log("Error: " + e.message); }}## g.elasticsearch.* — Elasticsearch
Sección titulada «## g.elasticsearch.* — Elasticsearch»Soporte nativo para consultar e indexar datos en clústeres Elasticsearch externos mediante Elastic.Clients.Elasticsearch. El parámetro conn es el nombre de una credencial que contiene el objeto JSON de conexión (url y opcionalmente apiKey o username/password). Bloqueado para scripts originados por MCP.
| Método | Firma | Async | Descripción |
|---|---|---|---|
ping | (conn) → Promise<boolean> | Sí | Verifica la conexión al clúster; devuelve true si tiene éxito |
info | (conn) → Promise<ElasticsearchInfoResult> | Sí | Recupera metadatos del clúster: nombre, versión, tagline, etc. |
createIndex | (conn, indexName, mappingJson?) → Promise<boolean> | Sí | Crea un índice con un mapping JSON opcional |
deleteIndex | (conn, indexName) → Promise<boolean> | Sí | Elimina un índice existente |
index | (conn, indexName, id, document) → Promise<boolean> | Sí | Indexa un único objeto JS en el clúster |
get | (conn, indexName, id) → Promise<any> | Sí | Recupera un documento por ID; devuelve el objeto _source parseado |
bulk | (conn, indexName, documents, chunkSize?) → Promise<ElasticsearchBulkResult> | Sí | Ingesta de alto rendimiento; divide arrays grandes para evitar límites de payload |
search | (conn, indexName, queryDsl) → Promise<any> | Sí | Ejecuta un Query DSL JSON bruto como cadena u objeto JS y devuelve hits deserializados |
ElasticsearchInfoResult:
{ name: string clusterName: string clusterUuid: string version: string tagline: string}ElasticsearchBulkResult:
{ total: number successful: number failed: number}Ejemplo
Sección titulada «Ejemplo»async function main() { const conn = "my-elastic"; // secret name
// Check connection const isUp = await g.elasticsearch.ping(conn); if (!isUp) return g.log("Connection failed");
// Bulk index documents const docs = [{ id: 1, text: "A" }, { id: 2, text: "B" }]; const bulkRes = await g.elasticsearch.bulk(conn, "products", docs, 1000); g.log(`Indexed ${bulkRes.successful} out of ${bulkRes.total}`);
// Query DSL search const searchRes = await g.elasticsearch.search(conn, "products", { query: { match_all: {} } }); g.log(`Total hits: ${searchRes.hits.total.value}`);}