### Results Event Example Input Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/reference/events-logging.mdx An example of input parameters for a 'get' operation that would trigger a 'results' event. This shows the data structure before the query is executed. ```typescript const prop1 = "22874c81-27c4-4264-92c3-b280aa79aa30"; const prop2 = "366aade8-a7c0-4328-8e14-0331b185de4e"; entity.get({ prop1, prop2 }).go(); ``` -------------------------------- ### DynamoDB Client Initialization (v2) Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/reference/dynamodb-client.mdx Example of initializing the v2 AWS SDK DynamoDB DocumentClient. This client is compatible with ElectroDB. ```typescript import { DocumentClient } from "aws-sdk/clients/dynamodb"; const client = new DocumentClient({ region: "us-east-1", }); ``` -------------------------------- ### Patch Item Example Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/mutations/patch.mdx This example demonstrates how to use the patch method to update an item, including setting attributes, adding to lists, and applying conditions. ```APIDOC ## POST /patch ### Description Safely patches an existing item in the database. Unlike `update`, `patch` ensures that the item must exist before applying changes, preventing accidental item creation. ### Method POST ### Endpoint `/patch` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body This endpoint does not directly accept a request body in the traditional sense. The operation is defined through a fluent API. ### Request Example ```typescript tasks .patch({ team: "core", task: "45-662", project: "backend" }) .set({ status: "open" }) .add({ points: 5 }) .append({ comments: [ { user: "janet", body: "This seems half-baked." } ] }) .where(({ status }, { eq }) => eq(status, "in-progress")) .go(); ``` ### Response #### Success Response (200) Returns the identifiers of the patched item. - **data** (EntityIdentifiers) - The identifiers of the updated item. #### Response Example ```json { "data": { "team": "core", "task": "45-662", "project": "backend" } } ``` ### Equivalent Parameters ```json { "UpdateExpression": "SET #status = :status_u0, #comments = list_append(#comments, :comments_u0), #updatedAt = :updatedAt_u0, #gsi1sk = :gsi1sk_u0, #team = :team_u0, #project = :project_u0, #task = :task_u0, #__edb_e__ = :__edb_e___u0, #__edb_v__ = :__edb_v___u0 ADD #points :points_u0", "ExpressionAttributeNames": { "#pk": "pk", "#sk": "sk", "#status": "status", "#points": "points", "#comments": "comments", "#updatedAt": "updatedAt", "#gsi1sk": "gsi1sk", "#team": "team", "#project": "project", "#task": "task", "#__edb_e__": "__edb_e__", "#__edb_v__": "__edb_v__" }, "ExpressionAttributeValues": { ":status0": "in-progress", ":status_u0": "open", ":points_u0": 5, ":comments_u0": [ { "user": "janet", "body": "This seems half-baked." } ], ":updatedAt_u0": 1692723798360, ":gsi1sk_u0": "$assignments#tasks_1#status_open", ":team_u0": "core", ":project_u0": "backend", ":task_u0": "45-662", ":__edb_e___u0": "tasks", ":__edb_v___u0": "1" }, "TableName": "your_table_name", "Key": { "pk": "$taskapp#team_core", "sk": "$tasks_1#project_backend#task_45-662" }, "ConditionExpression": "attribute_exists(#pk) AND attribute_exists(#sk) AND #status = :status0" } ``` ``` -------------------------------- ### DynamoDB Client Initialization (v3) Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/reference/dynamodb-client.mdx Example of initializing the v3 AWS SDK DynamoDBClient. This client is compatible with ElectroDB when used with DynamoDBDocumentClient. ```typescript import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; const client = new DynamoDBClient({ region: "us-east-1", }); ``` -------------------------------- ### ElectroDB Setup: DynamoDBClient, Entity, Service Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/mutations/transact-write.mdx Essential imports and client initialization for using ElectroDB. This setup is required for defining entities and services used in transactions. ```typescript import { DynamoDBClient } from '@aws-sdk/client-dynamodb'; import { Entity, Service } from 'electrodb'; const table = 'electro'; const client = new DynamoDBClient({}); ``` -------------------------------- ### Duplicate Indexes Example Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/reference/errors.mdx Provides an example of a model configuration that contains duplicate index names, which will result in a 'Duplicate Indexes' error (Code: 1004). ```javascript { indexes: { index1: { index: "idx1", // <-- duplicate "idx1" pk: {}, sk: {} }, index2: { index: "idx1", // <-- duplicate "idx1" pk: {}, sk: {} } } } ``` -------------------------------- ### Results Event Example Output Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/reference/events-logging.mdx An example of the JSON output for a 'results' event after a successful 'get' operation. This includes the returned item and confirmation of success. ```typescript { "type": "results", "method": "get", "config": { }, "success": true, "results": { "Item": { "prop2": "366aade8-a7c0-4328-8e14-0331b185de4e", "sk": "$testcollection#entity_1#prop2_366aade8-a7c0-4328-8e14-0331b185de4e", "prop1": "22874c81-27c4-4264-92c3-b280aa79aa30", "prop3": "3ec9ed0c-7497-4d05-bdb8-86c09a618047", "__edb_e__": "entity", "__edb_v__": "1", "pk": "$test_1#prop1_22874c81-27c4-4264-92c3-b280aa79aa30" } } } ``` -------------------------------- ### Query Event Example Input Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/reference/events-logging.mdx An example of input parameters for an 'update' operation that would trigger a 'query' event. This shows the data structure before it's sent to DynamoDB. ```typescript const prop1 = "22874c81-27c4-4264-92c3-b280aa79aa30"; const prop2 = "366aade8-a7c0-4328-8e14-0331b185de4e"; const prop3 = "3ec9ed0c-7497-4d05-bdb8-86c09a618047"; entity.update({ prop1, prop2 }).set({ prop3 }).go(); ``` -------------------------------- ### Instantiate Entity with DynamoDB Client (v3) Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/reference/dynamodb-client.mdx Supply a v3 DynamoDB DocumentClient when creating a new Entity instance. Ensure the aws-sdk/lib-dynamodb and aws-sdk/client-dynamodb packages are installed. ```typescript import { Entity } from "electrodb"; import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb"; const table = "my_table_name"; const client = DynamoDBDocumentClient.from( new DynamoDBClient({ region: "us-east-1" }), ); const task = new Entity( { // your model }, { client, table, }, ); ``` -------------------------------- ### Define ElectroDB Entity Access Pattern Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/queries/query.mdx An example of how to configure an entity index with composite attributes for partition and sort keys. ```json { "units": { "index": "gsi1pk-gsi1sk-index", "pk": { "field": "gsi1pk", "composite": ["mallId"] }, "sk": { "field": "gsi1sk", "composite": ["buildingId", "unitId"] } } } ``` -------------------------------- ### Exhausting Pagination with a Loop Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/queries/pagination.mdx A practical example of using a do-while loop to automatically fetch all pages of a query result until the cursor is null. ```typescript import { EntityItem, QueryResponse } from "electrodb"; import { users } from "./entities"; type UserItem = EntityItem; type UserQueryResponse = QueryResponse; async function getTeamMembers(team: string) { let members: UserItem[] = []; let cursor = null; do { const results: UserQueryResponse = await users.query .members({ team }) .go({ cursor }); members = [...members, ...results.data]; cursor = results.cursor; } while (cursor !== null); return members; } ``` -------------------------------- ### Invalid ElectroDB Query Examples Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/queries/query.mdx Examples of query attempts that will fail or behave unexpectedly due to missing required Partition Key attributes or incorrect Sort Key ordering. ```typescript // Throws: Missing PK await StoreLocations.query.stores().go(); // Throws: Missing PK component await StoreLocations.query.stores({ mallId: "EastPointe" }).go(); // Ignores unitId: Missing intermediate SK component await StoreLocations.query.stores({ cityId: "Atlanta1", mallId: "EastPointe", unitId: "B24" }).go(); ``` -------------------------------- ### Transact Write Example Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/mutations/transact-write.mdx Perform multiple write operations atomically using the transact-write API. This ensures all operations succeed or fail together. ```typescript await db.users.transactWrite({ create: [ { id: 'user1', email: 'user1@example.com' }, { id: 'user2', email: 'user2@example.com' }, ], update: [ { id: 'user1', email: 'user1-updated@example.com', }, ], delete: [ { id: 'user2' }, ], }); ``` -------------------------------- ### Query Event Example Output Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/reference/events-logging.mdx The JSON output representing a 'query' event for an 'update' operation. This illustrates the detailed parameters and configuration captured by ElectroDB before execution. ```json { "type": "query", "method": "update", "params": { "UpdateExpression": "SET #prop3 = :prop3_u0, #prop1 = :prop1_u0, #prop2 = :prop2_u0, #__edb_e__ = :__edb_e___u0, #__edb_v__ = :__edb_v___u0", "ExpressionAttributeNames": { "#prop3": "prop3", "#prop1": "prop1", "#prop2": "prop2", "#__edb_e__": "__edb_e__", "#__edb_v__": "__edb_v__" }, "ExpressionAttributeValues": { ":prop3_u0": "3ec9ed0c-7497-4d05-bdb8-86c09a618047", ":prop1_u0": "22874c81-27c4-4264-92c3-b280aa79aa30", ":prop2_u0": "366aade8-a7c0-4328-8e14-0331b185de4e", ":__edb_e___u0": "entity", ":__edb_v___u0": "1" }, "TableName": "electro", "Key": { "pk": "$test#prop1_22874c81-27c4-4264-92c3-b280aa79aa30", "sk": "$testcollection#entity_1#prop2_366aade8-a7c0-4328-8e14-0331b185de4e" } }, "config": {} } ``` -------------------------------- ### Query a Collection by Employee ID Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/queries/collection.mdx This example shows how to query the 'assignments' collection using a specific employee ID. This is a direct way to retrieve all assignments for a given employee. ```javascript const results = await TaskApp.collections .assignments({ employeeId: "JExotic" }) .go(); ``` -------------------------------- ### Instantiating Service with DocClient Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/reference/errors.mdx Shows how to provide a DynamoDB DocClient when instantiating a Service, enabling it to interact with DynamoDB. ```javascript new Service("", { client }); ``` -------------------------------- ### Initialize EmployeeApp Service Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/examples/human-resources.mdx Sets up the 'EmployeeApp' service by joining the 'Employee', 'Task', and 'Office' entities. It requires AWS SDK clients and a table name for initialization. ```javascript const { DynamoDBClient } = require("@aws-sdk/client-dynamodb"); const { DynamoDBDocumentClient } = require("@aws-sdk/lib-dynamodb"); const client = DynamoDBDocumentClient.from( new DynamoDBClient({ region: "us-east-1" }), ); const { Service } = require("electrodb"); const table = "projectmanagement"; const EmployeeApp = new Service( { employees: Employee, tasks: Task, offices: Office, }, { client, table }, ); ``` -------------------------------- ### Get Item with Composite Attributes Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/queries/get.mdx Use the `get` method with all composite attributes to retrieve an item. If no record is found, `null` is returned. ```typescript const results = await StoreLocations.get({ storeId: "LatteLarrys", mallId: "EastPointe", buildingId: "F34", cityId: "Atlanta1", }).go(); ``` -------------------------------- ### Get a Single Book Record Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/core-concepts/quick-start.mdx Use the 'get' method to retrieve a specific book record by its primary key (bookId and storeId). ```typescript const book = await Book.get({ bookId: "beedabe8-e34e-4d41-9272-0755be9a2a9f", storeId: "pdx-45", }).go(); ``` -------------------------------- ### Collection Query Example in TypeScript Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/modeling/collections.mdx An example of how to perform a Collection Query in ElectroDB using TypeScript. This query targets assignments for a specific employee. ```typescript await TaskApp.collections.assignments({ employeeId: "JExotic" }).go(); ``` -------------------------------- ### Using the 'overview' Collection Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/modeling/collections.mdx The 'overview' collection is typically defined on the table's Primary Index, using `projectId` as the Partition Key. Entities that share this composite key can be part of this collection. This example demonstrates how to interact with the 'overview' collection. ```typescript const service = new Service({ models: { tasks: { ... }, projectMembers: { ... }, }, // ... }); // Example of using the 'overview' collection const overviewCollection = service.collections.overview; ``` -------------------------------- ### Querying with Full vs Partial Data Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/queries/query.mdx Demonstrates the difference between querying with full known data versus using the .begins() method for partial data matching. ```typescript // Full data query StoreLocations.query.units({ mallId, buildingId }).go(); // Partial data query using begins StoreLocations.query.units({ mallId }).begins({ buildingId }).go(); ``` -------------------------------- ### Response Format for Get Operation Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/queries/get.mdx The `get` operation returns an object containing the retrieved item data or `null` if not found, along with an optional cursor. ```typescript { data: EntityItem | null, cursor: string | undefined } ``` -------------------------------- ### ElectroDB Match Query Example Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/queries/match.mdx Demonstrates how to use the Match method to query store locations with specific criteria. This method leverages attributes to select the best index and includes all supplied values in a query filter. ```typescript await StoreLocations.find({ mallId: "EastPointe", buildingId: "BuildingA1", leaseEndDate: "2020-03-22", rent: "1500.00", }).go(); ``` -------------------------------- ### Entity Query Example in TypeScript Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/modeling/collections.mdx An example of how to perform an Entity Query in ElectroDB using TypeScript. This query targets tasks assigned to a specific employee. ```typescript await TaskApp.entities.task.query.assigned({ employeeId: "JExotic" }).go(); ``` -------------------------------- ### Passing DocClient at Query Time Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/reference/errors.mdx Illustrates how to dynamically provide a DocClient within the `go()` options of an entity query, useful for flexible client management. ```javascript await entity.get({ id }).go({ client }); ``` -------------------------------- ### Define ElectroDB Model with Basic Index Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/modeling/indexes.mdx This example shows how to define a basic ElectroDB model with entity, service, and version information. It includes attribute definitions and a simple index configuration using a primary key (pk) and sort key (sk) template. ```typescript { model: { entity: "your_entity_name", service: "your_service_name", version: "1" }, attributes: { accountId: { type: "string" // string and number types are both supported } }, indexes: { "your_access_pattern_name": { pk: { field: "accountId", composite: ["accountId"], template: "${accountId}" }, sk: {} } } } ``` -------------------------------- ### Equivalent DynamoDB Parameters for Get Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/queries/get.mdx This JSON object shows the equivalent parameters that would be used in a direct DynamoDB `GetItem` operation for the ElectroDB `get` call. ```json { "Key": { "pk": "$mallstoredirectory#cityid_atlanta1#mallid_eastpointe", "sk": "$mallstore_1#buildingid_f34#storeid_lattelarrys" }, "TableName": "YOUR_TABLE_NAME" } ``` -------------------------------- ### Project Overview Equivalent Parameters Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/modeling/collections.mdx Shows the equivalent DynamoDB parameters for a query targeting the 'overview' collection, demonstrating how ElectroDB translates collection queries into low-level DynamoDB operations. ```json { "KeyConditionExpression": "#pk = :pk and begins_with(#sk1, :sk1)", "TableName": "projectmanagement", "ExpressionAttributeNames": { "#pk": "pk", "#sk1": "sk" }, "ExpressionAttributeValues": { ":pk": "$taskapp#projectid_sd-204", ":sk1": "$overview" } } ``` -------------------------------- ### Batch Get Response Format Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/queries/batch-get.mdx The response from a batch get operation includes `data` containing the retrieved items and `unprocessed` containing any items that could not be processed. ```typescript { data: Array, unprocessed: Array } ``` -------------------------------- ### Configure Multi-language Project Structure Source: https://github.com/tywalch/electrodb/blob/master/www/README.md Demonstrates the directory structure required to support multiple languages in an Astro project by adding language-specific folders under src/pages. ```diff 📂 src/pages ┣ 📂 en ┃ ┣ 📜 page-1.md ┃ ┣ 📜 page-2.md ┃ ┣ 📜 page-3.astro + ┣ 📂 es + ┃ ┣ 📜 page-1.md + ┃ ┣ 📜 page-2.md + ┃ ┣ 📜 page-3.astro ``` -------------------------------- ### Deterministic ClientRequestToken Example Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/mutations/transact-write.mdx Provides an example of generating a deterministic ClientRequestToken for ensuring idempotency. A unique token guarantees that an operation is performed only once within DynamoDB's timing window. ```typescript const token = "daily-headcount-count-2022-03-16"; ``` -------------------------------- ### Create a Service with Entities Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/modeling/services.mdx Instantiate a Service by providing a map of entities and their aliases. Optionally, configure the Service with a DynamoDB table and client. ```typescript import { Service } from "electrodb"; const TaskApp = new Service( { employee: Employee, task: Task, }, { table, client }, ); ``` -------------------------------- ### Attribute Name Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/mutations/conditions.mdx Use the `name` function to get the attribute name for use in expressions. ```javascript name(rent) ``` -------------------------------- ### Instantiate Service with DynamoDB Client (v3) Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/reference/dynamodb-client.mdx Provide a v3 DynamoDB DocumentClient during the instantiation of an ElectroDB Service. This client will be shared across all entities within the service. ```typescript import { Entity, Service } from "electrodb"; import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb"; const table = "my_table_name"; const client = DynamoDBDocumentClient.from( new DynamoDBClient({ region: "us-east-1" }), ); const task = new Entity({ // your model }); const user = new Entity({ // your model }); const service = new Service( { task, user }, { client, table, }, ); ``` -------------------------------- ### Instantiating Entity with DocClient Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/reference/errors.mdx Demonstrates how to pass a DynamoDB DocClient to an Entity constructor, which is required for ElectroDB to perform queries. ```javascript new Entity(schema, { client }); ``` -------------------------------- ### ElectroDB Entity Definition Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/reference/conversions.mdx Defines an ElectroDB entity with its model, attributes, and indexes. This setup is necessary before utilizing conversion utilities. ```typescript import { Entity, createConversions } from "electrodb"; const thing = new Entity( { model: { entity: "thing", version: "1", service: "thingstore", }, attributes: { organizationId: { type: "string", }, accountId: { type: "string", }, name: { type: "string", }, description: { type: "string", }, }, indexes: { records: { pk: { field: "pk", composite: ["organizationId"], }, sk: { field: "sk", composite: ["accountId"], }, }, }, }, { table: "my_table" }, ); ``` -------------------------------- ### Parse DocumentClient Responses Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/reference/parse.mdx Use the parse method to format results from various DocumentClient operations like get, query, and update. ```typescript const myEntity = new Entity({...}); const getResults = await docClient.send(new GetCommand({...})); const queryResults = await docClient.send(new QueryCommand({...})); const updateResults = await docClient.send(new UpdateCommand({...})); const formattedGetResults = myEntity.parse(getResults); const formattedQueryResults = myEntity.parse(queryResults); ``` -------------------------------- ### Query Project Overview Collection Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/modeling/collections.mdx Fetches an overview of a project, including tasks and project members, using the 'overview' collection. This is a simple collection query. ```typescript // overview const results = await TaskApp.collections .overview({ projectId: "SD-204" }) .go(); ``` -------------------------------- ### Query Lease Agreements with Comparison Operators Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/queries/query.mdx Demonstrates how to use comparison operators like lt, lte, and between to filter lease agreements by date ranges within ElectroDB. ```typescript await StoreLocations.query .leases({ storeId: "LatteLarrys" }) .lt({ leaseEndDate: "2021-00-00" }) .go(); await StoreLocations.query .leases({ storeId: "LatteLarrys" }) .lte({ leaseEndDate: "2021-02-00" }) .go(); await StoreLocations.query .leases({ storeId: "LatteLarrys" }) .between({ leaseEndDate: "2010-00-00" }, { leaseEndDate: "2020-99-99" }) .go(); ``` -------------------------------- ### Entity Pagination with Cursors Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/queries/pagination.mdx Demonstrates how to perform an initial query and use the returned cursor to fetch subsequent pages of data from an ElectroDB entity. ```typescript const results1 = await MallStores.query.leases({ mallId }).go(); const results2 = await MallStores.query.leases({ mallId }) .go({ cursor: results1.cursor }); ``` -------------------------------- ### Define Secondary Index with Composite Attributes Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/mutations/patch.mdx Example configuration for a secondary index using composite attributes for primary and sort keys. ```json { "index": "my-gsi", "pk": { "field": "gsi1pk", "composite": ["attr1"] }, "sk": { "field": "gsi1sk", "composite": ["attr2", "attr3"] } } ``` -------------------------------- ### Specify Attributes for ProjectionExpression Source: https://github.com/tywalch/electrodb/blob/master/www/src/partials/query-options.mdx The `attributes` option allows you to define which attributes should be included in the ProjectionExpression for `get` or `query` operations. By default, all attributes are returned. ```typescript attributes?: string[]; ``` -------------------------------- ### ElectroDB Model with Key Template and Static Prefixes/Postfixes Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/modeling/indexes.mdx Demonstrates an advanced ElectroDB model configuration where string attributes are used as index keys. It showcases the use of key templates with static prefixes and postfixes for the primary key (pk), allowing for structured key generation while maintaining a relationship with the attribute value. ```typescript { model: { entity: "your_entity_name", service: "your_service_name", version: "1" }, attributes: { accountId: { type: "string" // only string types are both supported for this example }, organizationId: { type: "string" }, name: { type: "string" } }, indexes: { "your_access_pattern_name": { pk: { field: "accountId", composite: ["accountId"], template: "prefix_${accountId}_postfix" }, sk: { field: "organizationId", composite: ["organizationId"] } } } } ``` ```typescript await myEntity .get({ accountId: "1111-2222-3333-4444", organizationId: "AAAA-BBBB-CCCC-DDDD", }) .go(); ``` ```json { "Key": { "accountId": "prefix_1111-2222-3333-4444_postfix", "organizationId": "aaaa-bbbb-cccc-dddd" }, "TableName": "your_table_name" } ``` ```json { "accountId": "prefix_1111-2222-3333-4444_postfix", "organizationId": "aaaa-bbbb-cccc-dddd" } ``` -------------------------------- ### Query Author and Book Access Patterns Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/examples/library-system.mdx Demonstrates various query patterns including filtering by author name, partial name matching, and retrieving collection-based data like author details, books, and genres. ```typescript // Query by last name const { data, cursor } = await author.query.writer({ authorLastName: "king" }).go(); // Query by last name and partial first name await author.query.writer({ authorLastName: "king" }).begins({ authorFirstName: "s" }).go(); // Query by full name await author.query.writer({ authorLastName: "smith", authorFirstName: "john" }).go(); // Retrieve collection data await library.collections.works({ authorLastName: "king", authorFirstName: "stephen" }).go().then((works) => { const [writer] = works.data.author; const books = works.data.book; const genres = works.data.genre; return { writer, books, genres }; }); ``` -------------------------------- ### Get member information by memberId Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/examples/library-system.mdx Retrieves detailed information for a specific member using their unique member ID. It queries the 'member' collection. ```typescript const { data, cursor } = await member.query .member({ memberId: "0000001" }) .go(); ``` -------------------------------- ### Get books within a genre Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/examples/library-system.mdx Retrieves a list of books that belong to a specified genre. It queries the 'categories' collection within the 'genre' module. ```typescript const { data, cursor } = await genre.query.categories({ genre: "horror" }).go(); ``` -------------------------------- ### Transact Get Execution Options Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/queries/transact-get.mdx These options can be provided to .params() and .go() to modify query behavior or add custom parameters. The client option allows per-request client selection, and abortSignal enables operation cancellation. ```typescript { client?: DocumentClient; abortSignal?: AbortSignal; } ``` -------------------------------- ### Initialize ElectroDB Service Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/examples/library-system.mdx Aggregates multiple entities into a single ElectroDB service instance for unified access. ```typescript import { Service } from "electrodb"; const library = new Service({ author, book, genre, member }); ``` -------------------------------- ### Get books/copies by title Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/examples/library-system.mdx Retrieves books or book copies based on their title. This query uses the 'releases' collection and filters by the 'bookTitle' field. ```typescript const { data, cursor } = await book.query.releases({ bookTitle: "it" }).go(); ``` -------------------------------- ### Transact Write with Execution Options (go) Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/mutations/transact-write.mdx Execute a transact-write operation with custom execution options using the `.go()` method. This allows for dynamic client selection, request tokens, and abort signals. ```typescript const options = { client: myDynamoDbClient, token: 'my-client-request-token', abortSignal: myAbortSignal }; await db.users.transactWrite(options).go({ create: [ { id: 'user1', email: 'user1@example.com' }, { id: 'user2', email: 'user2@example.com' }, ], update: [ { id: 'user1', email: 'user1-updated@example.com', }, ], delete: [ { id: 'user2' }, ], }); ``` -------------------------------- ### Common ElectroDB Query Operations Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/queries/query.mdx Examples of various query operations including exact matches, begins with, and range comparisons like greater than. ```typescript // Lease Agreements by StoreId await StoreLocations.query.leases({ storeId: "LatteLarrys" }).go(); // Lease Agreement by StoreId for specific date await StoreLocations.query.leases({ storeId: "LatteLarrys", leaseEndDate: "2020-03-22" }).go(); // Lease agreements by StoreId for 2020 using begins await StoreLocations.query.leases({ storeId: "LatteLarrys" }).begins({ leaseEndDate: "2020-00-00" }).go(); // Lease Agreements by StoreId after March 2020 await StoreLocations.query.leases({ storeId: "LatteLarrys" }).gt({ leaseEndDate: "2020-04-00" }).go(); // Lease Agreements by StoreId after, and including, March 2020 await StoreLocations.query.leases({ storeId: "LatteLarrys" }).gte({ leaseEndDate: "2020-03-00" }).go(); ``` -------------------------------- ### Creating Virtual Attributes Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/recipes/virtual-attribute.mdx This example demonstrates how to define a virtual attribute 'displayPrice' that formats the 'price' attribute on retrieval. The 'watch' property ensures it reacts to changes in 'price', and the 'set' property prevents it from being written back to the database. ```APIDOC ## Creating Virtual Attributes ### Description Virtual attributes are attributes that might react to the retrieval of other attributes. The values for these attributes are transformed on retrieval, and are not persisted to DynamoDB. In this example we have an attribute `"displayPrice"` that needs its getter called anytime an item's `"price"` attribute is retrieved. The attribute `"displayPrice"` uses `watch` to return a formatted price string based whenever an item with a `"price"` attribute is queried. Additionally, `"displayPrice"` always returns `undefined` from its setter callback to ensure that it will never write data back to the table. ### Method N/A (Schema Definition) ### Endpoint N/A (Schema Definition) ### Parameters N/A ### Request Example N/A ### Response N/A ```typescript { model: { entity: "services", service: "costEstimator", version: "1" }, attributes: { service: { type: "string" }, price: { type: "number", required: true }, displayPrice: { type: "string", watch: ["price"], get: (_, {price}) => { return "$" + price; }, set: () => undefined } }, indexes: { pricing: { pk: { field: "pk", composite: ["service"] }, sk: { field: "sk", composite: [] } } } } ``` ``` -------------------------------- ### Get books within a genre and subgenre Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/examples/library-system.mdx Fetches books that belong to a specific genre and a particular subgenre. This query requires both genre and subgenre parameters. ```typescript const { data, cursor } = await genre.query .categories({ genre: "horror", subgenre: "killer clowns" }) .go(); ``` -------------------------------- ### Get genres and subgenres associated with a book Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/examples/library-system.mdx Retrieves the genres and subgenres associated with a specific book, identified by its ISBN or title. It queries the 'genre' collection. ```typescript await genre.query.book({ isbn: "9783453435773" }).go(); await genre.query.title({ bookTitle: "it" }).go(); ``` -------------------------------- ### Batch Delete - Equivalent Parameters Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/mutations/batch-delete.mdx Illustrates the DynamoDB `RequestItems` structure for a batch delete operation, showing how ElectroDB translates composite attributes into DynamoDB keys. ```APIDOC ## Equivalent DynamoDB Parameters for Batch Delete ### Description This section shows the underlying DynamoDB `RequestItems` structure that ElectroDB generates for a batch delete operation. It highlights how composite attributes are mapped to DynamoDB's `Key` structure. ### RequestItems Structure ```json { "RequestItems": { "YourTableName": [ { "DeleteRequest": { "Key": { "pk": "your_partition_key_value", "sk": "your_sort_key_value" } } }, { "DeleteRequest": { "Key": { "pk": "another_partition_key_value", "sk": "another_sort_key_value" } } } // ... more delete requests ] } } ``` ### Mapping Composite Attributes ElectroDB translates the composite attributes provided in the `delete` method (e.g., `storeId`, `mallId`, `buildingId`, `cityId`) into the appropriate `pk` and `sk` values for the DynamoDB `Key` object, based on your table's schema definition. ``` -------------------------------- ### Get All User Data for Initial Page Load Source: https://github.com/tywalch/electrodb/blob/master/www/src/pages/en/examples/version-control.mdx Aggregates issues, pull requests, repositories, and user information for a given username. It uses a `do-while` loop to fetch all data, handling pagination until all records are retrieved. ```typescript export async function getFirstPageLoad(username: string) { const results: OwnedItems = { issues: [], pullRequests: [], repositories: [], users: [], }; let next = null; do { const { cursor, data } = await store.collections.owned({ username }).go(); results.issues = results.issues.concat(data.issues); results.pullRequests = results.pullRequests.concat(data.pullRequests); results.repositories = results.repositories.concat(data.repositories); results.users = results.users.concat(data.users); next = cursor; } while (next !== null); return results; } ```