### Run Express + EventStoreDB Sample Source: https://github.com/event-driven-io/emmett/blob/main/src/docs/samples/index.md Instructions to access the EventStoreDB sample directory, start EventStoreDB using Docker, install dependencies, and run the Express.js application. ```bash cd emmett/samples/webApi/expressjs-with-esdb docker-compose up -d npm install npm run start ``` -------------------------------- ### Run Express + MongoDB Sample Source: https://github.com/event-driven-io/emmett/blob/main/src/docs/samples/index.md Steps to navigate to the MongoDB sample directory, start MongoDB with Docker, install dependencies, and run the Express.js application. ```bash cd emmett/samples/webApi/expressjs-with-mongodb docker-compose up -d npm install npm run start ``` -------------------------------- ### EventStoreDB Setup Source: https://github.com/event-driven-io/emmett/blob/main/src/docs/samples/index.md Example demonstrating the setup for an EventStoreDB event store using `getEventStoreDBEventStore` from the Emmett EventStoreDB package, including client initialization. ```typescript // EventStoreDB setup import { getEventStoreDBEventStore } from '@event-driven-io/emmett-esdb'; import { EventStoreDBClient } from '@eventstore/db-client'; const client = EventStoreDBClient.connectionString( 'esdb://localhost:2113?tls=false', ); const eventStore = getEventStoreDBEventStore(client); ``` -------------------------------- ### Basic Fastify App Setup Source: https://github.com/event-driven-io/emmett/blob/main/src/docs/frameworks/fastify.md Initialize the Fastify application with Emmett's API handlers and start the server. ```typescript import { startAPI, getFastifyApp } from '@event-driven-io/emmett-fastify'; import { getInMemoryEventStore } from '@event-driven-io/emmett'; const eventStore = getInMemoryEventStore(); const app = getFastifyApp({ apis: [shoppingCartApi(eventStore)], }); await startAPI(app, { port: 3000 }); ``` -------------------------------- ### Clone Repository and Install Dependencies Source: https://github.com/event-driven-io/emmett/blob/main/src/docs/resources/contributing.md Clone the Emmett repository, navigate into the directory, install project dependencies, and build all packages. This is the initial setup for development. ```bash git clone https://github.com/event-driven-io/emmett.git cd emmett npm install npm run build npm run test ``` -------------------------------- ### Basic Application Setup with Emmett Fastify Source: https://github.com/event-driven-io/emmett/blob/main/src/packages/emmett-fastify/README.md Set up a basic Fastify application with Emmett for event-sourced APIs. This includes creating an event store, defining routes, and starting the API server. ```typescript import { getApplication, startAPI } from '@event-driven-io/emmett-fastify'; import { getInMemoryEventStore } from '@event-driven-io/emmett'; import type { FastifyInstance } from 'fastify'; // Create your event store const eventStore = getInMemoryEventStore(); // Define your routes const registerRoutes = (app: FastifyInstance) => { app.get('/health', async () => ({ status: 'ok' })); app.post('/carts/:cartId/items', async (request, reply) => { // Handle command with event store return reply.code(201).send(); }); }; // Create and start the application const app = await getApplication({ registerRoutes }); await startAPI(app, { port: 3000 }); ``` -------------------------------- ### Basic Event Store Setup with Connection String Source: https://github.com/event-driven-io/emmett/blob/main/src/packages/emmett-mongodb/README.md Set up the MongoDB event store using a connection string. This example demonstrates defining event types, appending events to a stream, reading events, and closing the store connection. ```typescript import { getMongoDBEventStore, toStreamName, } from '@event-driven-io/emmett-mongodb'; import { type Event, STREAM_DOES_NOT_EXIST } from '@event-driven-io/emmett'; // Define your events type ProductItemAdded = Event< 'ProductItemAdded', { productItem: { productId: string; quantity: number; price: number } } >; type DiscountApplied = Event< 'DiscountApplied', { percent: number; couponId: string } >; type ShoppingCartEvent = ProductItemAdded | DiscountApplied; // Create event store with connection string const eventStore = getMongoDBEventStore({ connectionString: 'mongodb://localhost:27017/mydb', }); // Append events to a stream const streamName = toStreamName('shopping_cart', 'cart-123'); await eventStore.appendToStream( streamName, [ { type: 'ProductItemAdded', data: { productItem: { productId: 'prod-1', quantity: 2, price: 29.99 } }, }, ], { expectedStreamVersion: STREAM_DOES_NOT_EXIST }, ); // Read events from stream const { events, currentStreamVersion } = await eventStore.readStream(streamName); // Close the event store when done (only needed when using connection string) await eventStore.close(); ``` -------------------------------- ### Complete Example Source: https://github.com/event-driven-io/emmett/blob/main/src/docs/frameworks/fastify.md A comprehensive example demonstrating Fastify integration with PostgreSQL event store and custom API definitions. ```APIDOC ## Complete Example ```typescript import { startAPI, getFastifyApp } from '@event-driven-io/emmett-fastify'; import { getPostgreSQLEventStore } from '@event-driven-io/emmett-postgresql'; import { CommandHandler } from '@event-driven-io/emmett'; // Define your decider const shoppingCartDecider = { decide, evolve, initialState, mapToStreamId: (id: string) => `shopping_cart-${id}`, }; // Create event store const eventStore = getPostgreSQLEventStore(process.env.DATABASE_URL!); // Define API const shoppingCartApi = (eventStore: EventStore) => async (fastify: FastifyInstance) => { const handle = CommandHandler(shoppingCartDecider, eventStore); fastify.post<{ Params: { cartId: string }; Body: { productId: string; quantity: number }; }>('/carts/:cartId/items', async (request, reply) => { const { cartId } = request.params; const { productId, quantity } = request.body; const price = await getPriceFromCatalog(productId); const result = await handle(cartId, { type: 'AddProductItem', data: { productId, quantity, price }, }); return reply .header('ETag', `"${result.nextExpectedStreamVersion}"`) .status(200) .send({ added: true }); }); }; // Start server const app = getFastifyApp({ apis: [shoppingCartApi(eventStore)], }); await startAPI(app, { port: 3000 }); ``` ``` -------------------------------- ### Setup PostgreSQL for E2E Testing Source: https://github.com/event-driven-io/emmett/blob/main/src/docs/guides/testing.md Configure and start a PostgreSQL container using Testcontainers for end-to-end testing of your application. ```typescript import { ApiE2ESpecification } from '@event-driven-io/emmett-expressjs'; import { getPostgreSQLEventStore } from '@event-driven-io/emmett-postgresql'; import { PostgreSqlContainer, StartedPostgreSqlContainer, } from '@testcontainers/postgresql'; describe('Shopping Cart API (E2E)', () => { let postgres: StartedPostgreSqlContainer; let given: ApiE2ESpecification; beforeAll(async () => { // Start PostgreSQL container postgres = await new PostgreSqlContainer().start(); const eventStore = getPostgreSQLEventStore(postgres.getConnectionUri()); given = ApiE2ESpecification.for(() => getApplication({ apis: [shoppingCartApi(eventStore, getProductPrice)], }), ); }); afterAll(async () => { await eventStore.close(); await postgres.stop(); }); }); ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/event-driven-io/emmett/blob/main/samples/webApi/expressjs-with-mongodb/README.md Run this command to install all necessary Node.js packages for the project. ```bash npm install ``` -------------------------------- ### Start the Application Source: https://github.com/event-driven-io/emmett/blob/main/samples/webApi/expressjs-with-mongodb/README.md Execute this command to start the Emmett WebApi application locally. ```bash npm run start ``` -------------------------------- ### Start PostgreSQL and Observability Stack Source: https://github.com/event-driven-io/emmett/blob/main/samples/webApi/expressjs-with-postgresql/README.md Use this command to start the necessary PostgreSQL database and the observability stack (Tempo, Loki, Prometheus, Grafana) for monitoring the application. ```bash docker compose --profile observability up -d ``` -------------------------------- ### MongoDB Event Store Setup Source: https://github.com/event-driven-io/emmett/blob/main/src/docs/samples/index.md Example of configuring the MongoDB event store using `getMongoDBEventStore` from the Emmett MongoDB package, specifying connection details and the database name. ```typescript // MongoDB event store setup import { getMongoDBEventStore } from '@event-driven-io/emmett-mongodb'; const eventStore = getMongoDBEventStore({ connectionString: 'mongodb://localhost:27017', database: 'shopping', }); ``` -------------------------------- ### Set up EventStoreDB for Testing with Testcontainers Source: https://github.com/event-driven-io/emmett/blob/main/src/docs/event-stores/esdb.md Provides an example of integrating EventStoreDB into testing workflows using Testcontainers. This snippet shows how to start a test container, obtain a client, and manage the container's lifecycle during tests. ```typescript import { getEventStoreDBTestContainer } from '@event-driven-io/emmett-testcontainers'; describe('EventStoreDB Tests', () => { let container: StartedEventStoreDBContainer; let client: EventStoreDBClient; beforeAll(async () => { container = await getEventStoreDBTestContainer().start(); client = container.getClient(); }); afterAll(async () => { await container.stop(); }); it('appends events', async () => { const eventStore = getEventStoreDBEventStore(client); // Test... }); }); ``` -------------------------------- ### Install Peer Dependencies Source: https://github.com/event-driven-io/emmett/blob/main/src/packages/emmett-sqlite/README.md Ensure you have the necessary peer dependencies installed. ```bash npm install @event-driven-io/emmett sqlite3 ``` -------------------------------- ### Run Emmett Setup Script Source: https://github.com/event-driven-io/emmett/blob/main/CONTRIBUTING.md Execute the setup script for Linux/macOS or Windows to configure the development environment. ```shell ./setup.sh ``` ```powershell .\buildScript.ps1 ``` -------------------------------- ### Subscription Start Options Source: https://github.com/event-driven-io/emmett/blob/main/src/packages/emmett-esdb/README.md Options for determining where to start subscription from. ```APIDOC ## Subscription Start Options ### Description Options for determining where to start subscription from. ### Values - **'BEGINNING'**: Start from the first event. - **'END'**: Start from current end (new events only). - **'CURRENT'**: Resume from last stored checkpoint. - **{ lastCheckpoint: bigint }**: Resume from specific position. ``` -------------------------------- ### Start API Source: https://github.com/event-driven-io/emmett/blob/main/src/docs/frameworks/expressjs.md Starts the Express.js API server. ```APIDOC ## Start API ### Description Starts the Express.js API server on the specified port. ### Method `startAPI(app, port)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript startAPI(app, 3000); ``` ### Response #### Success Response (200) Server starts listening on the specified port. #### Response Example (Server listening message) ``` -------------------------------- ### Install @event-driven-io/emmett-testcontainers Source: https://github.com/event-driven-io/emmett/blob/main/src/packages/emmett-testcontainers/README.md Install the package using your preferred package manager. You also need to install the EventStoreDB client as a peer dependency. ```bash npm add @event-driven-io/emmett-testcontainers # or pnpm add @event-driven-io/emmett-testcontainers # or yarn add @event-driven-io/emmett-testcontainers ``` ```bash npm add @eventstore/db-client ``` -------------------------------- ### Complete Fastify Example with PostgreSQL Source: https://github.com/event-driven-io/emmett/blob/main/src/docs/frameworks/fastify.md A full example demonstrating Fastify integration with a PostgreSQL event store, including decider definition, route handling, and server startup. ```typescript import { startAPI, getFastifyApp } from '@event-driven-io/emmett-fastify'; import { getPostgreSQLEventStore } from '@event-driven-io/emmett-postgresql'; import { CommandHandler } from '@event-driven-io/emmett'; // Define your decider const shoppingCartDecider = { decide, evolve, initialState, mapToStreamId: (id: string) => `shopping_cart-${id}`, }; // Create event store const eventStore = getPostgreSQLEventStore(process.env.DATABASE_URL!); // Define API const shoppingCartApi = (eventStore: EventStore) => async (fastify: FastifyInstance) => { const handle = CommandHandler(shoppingCartDecider, eventStore); fastify.post<{ Params: { cartId: string }; Body: { productId: string; quantity: number }; }>('/carts/:cartId/items', async (request, reply) => { const { cartId } = request.params; const { productId, quantity } = request.body; const price = await getPriceFromCatalog(productId); const result = await handle(cartId, { type: 'AddProductItem', data: { productId, quantity, price }, }); return reply .header('ETag', `"${result.nextExpectedStreamVersion}"`) .status(200) .send({ added: true }); }); }; // Start server const app = getFastifyApp({ apis: [shoppingCartApi(eventStore)], }); await startAPI(app, { port: 3000 }); ``` -------------------------------- ### Install Peer Dependencies Source: https://github.com/event-driven-io/emmett/blob/main/src/docs/event-stores/esdb.md Install the required peer dependencies for the EventStoreDB adapter. ```bash npm install @event-driven-io/emmett @eventstore/db-client ``` -------------------------------- ### Install Node.js LTS with NVM Source: https://github.com/event-driven-io/emmett/blob/main/CONTRIBUTING.md Use NVM to install and use the current recommended Node.js LTS version. ```shell nvm install ``` ```shell nvm use ``` -------------------------------- ### Define Example Commands Source: https://github.com/event-driven-io/emmett/blob/main/src/docs/quick-intro.md Provides example command objects for adding and removing items from the shopping cart. ```typescript const commands: Command[] = [ { type: "AddItem", data: { name: "Pizza" } }, { type: "AddItem", data: { name: "Ice Cream" }, }, { type: "RemoveItem", data: { name: "Ice Cream" }, }, ]; ``` -------------------------------- ### Install Dependencies with Bun Source: https://github.com/event-driven-io/emmett/blob/main/src/e2e/bun/README.md Use this command to install all necessary project dependencies using the Bun package manager. ```bash bun install ``` -------------------------------- ### Handle Example Commands Source: https://github.com/event-driven-io/emmett/blob/main/src/docs/quick-intro.md Processes a list of example commands using the handle function and event store. ```typescript const handleCommands = async (cartId: string) => { for (const command of commands) { const currentState = await eventStore.get(cartId, evolve, initialState); const events = handle(currentState, command); await eventStore.append(cartId, events); } }; ``` -------------------------------- ### Install Peer Dependencies Source: https://github.com/event-driven-io/emmett/blob/main/src/docs/event-stores/postgresql.md Install the required peer dependencies for the PostgreSQL event store. ```bash npm install @event-driven-io/emmett @event-driven-io/pongo ``` -------------------------------- ### Start MongoDB with Docker Compose Source: https://github.com/event-driven-io/emmett/blob/main/samples/webApi/expressjs-with-mongodb/README.md Use this command to start the MongoDB service required for the application. ```bash docker-compose up ``` -------------------------------- ### Start Nuxt 3 Development Server Source: https://github.com/event-driven-io/emmett/blob/main/src/e2e/esmCompatibility/README.md Run this command to start the local development server for your Nuxt 3 application. ```bash npm run dev ``` -------------------------------- ### Start the Emmett Application Source: https://github.com/event-driven-io/emmett/blob/main/samples/webApi/expressjs-with-postgresql/README.md Run this command to start the main Express.js application after setting up the database and observability stack. ```bash npm start ``` -------------------------------- ### Initialize and Start Podman Machine Source: https://github.com/event-driven-io/emmett/blob/main/src/docs/resources/faq.md Commands to initialize and start the Podman machine on macOS. Ensure Docker compatibility by exporting the DOCKER_HOST environment variable. ```bash podman machine init podman machine start export DOCKER_HOST="unix://$HOME/.local/share/containers/podman/machine/podman.sock" ``` -------------------------------- ### Install Peer Dependencies Source: https://github.com/event-driven-io/emmett/blob/main/src/docs/event-stores/mongodb.md Install the required peer dependencies for the MongoDB event store adapter. ```bash npm install @event-driven-io/emmett mongodb ``` -------------------------------- ### Shopping Cart API Example with Fastify Source: https://github.com/event-driven-io/emmett/blob/main/src/packages/emmett-fastify/README.md Complete example of the decider pattern with Fastify routes for a shopping cart. Includes event, command, and state definitions, decider implementation, and route registration. ```typescript import { DeciderCommandHandler, getInMemoryEventStore, type EventStore, type Decider, } from '@event-driven-io/emmett'; import { getApplication, startAPI } from '@event-driven-io/emmett-fastify'; import type { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify'; // Define events type ShoppingCartEvent = | { type: 'ShoppingCartOpened'; data: { cartId: string; clientId: string; openedAt: Date }; } | { type: 'ProductItemAdded'; data: { cartId: string; productId: string; quantity: number }; } | { type: 'ShoppingCartConfirmed'; data: { cartId: string; confirmedAt: Date }; }; // Define commands type ShoppingCartCommand = | { type: 'OpenShoppingCart'; data: { cartId: string; clientId: string; now: Date }; } | { type: 'AddProductItem'; data: { cartId: string; productId: string; quantity: number }; } | { type: 'ConfirmShoppingCart'; data: { cartId: string; now: Date } }; // Define state type ShoppingCart = | { status: 'Empty' } | { status: 'Pending'; id: string; clientId: string; items: Array<{ productId: string; quantity: number }>; } | { status: 'Confirmed'; id: string; confirmedAt: Date }; // Implement the decider const decider: Decider = { decide: (command, state) => { switch (command.type) { case 'OpenShoppingCart': return { type: 'ShoppingCartOpened', data: { cartId: command.data.cartId, clientId: command.data.clientId, openedAt: command.data.now, }, }; case 'AddProductItem': return { type: 'ProductItemAdded', data: { cartId: command.data.cartId, productId: command.data.productId, quantity: command.data.quantity, }, }; case 'ConfirmShoppingCart': return { type: 'ShoppingCartConfirmed', data: { cartId: command.data.cartId, confirmedAt: command.data.now }, }; } }, evolve: (state, event) => { switch (event.type) { case 'ShoppingCartOpened': return { status: 'Pending', id: event.data.cartId, clientId: event.data.clientId, items: [], }; case 'ProductItemAdded': if (state.status !== 'Pending') return state; return { ...state, items: [ ...state.items, { productId: event.data.productId, quantity: event.data.quantity }, ], }; case 'ShoppingCartConfirmed': if (state.status !== 'Pending') return state; return { status: 'Confirmed', id: state.id, confirmedAt: event.data.confirmedAt, }; } }, initialState: () => ({ status: 'Empty' }), }; // Create command handler const handle = DeciderCommandHandler(decider); // Register routes const registerRoutes = (eventStore: EventStore) => (app: FastifyInstance) => { app.post( '/clients/:clientId/shopping-carts', async (request: FastifyRequest, reply: FastifyReply) => { const { clientId } = request.params as { clientId: string }; const cartId = clientId; await handle(eventStore, cartId, { type: 'OpenShoppingCart', data: { cartId, clientId, now: new Date() }, }); return reply.code(201).send({ id: cartId }); }, ); app.post( '/clients/:clientId/shopping-carts/:cartId/items', async (request: FastifyRequest, reply: FastifyReply) => { const { cartId } = request.params as { cartId: string }; const { productId, quantity } = request.body as { productId: string; quantity: number; }; await handle(eventStore, cartId, { type: 'AddProductItem', data: { cartId, productId, quantity }, }); return reply.code(204).send(); }, ); app.post( '/clients/:clientId/shopping-carts/:cartId/confirm', async (request: FastifyRequest, reply: FastifyReply) => { const { cartId } = request.params as { cartId: string }; await handle(eventStore, cartId, { type: 'ConfirmShoppingCart', data: { cartId, now: new Date() }, }); return reply.code(204).send(); }, ); }; // Start the server const eventStore = getInMemoryEventStore(); const app = await getApplication({ registerRoutes: registerRoutes(eventStore), }); await startAPI(app, { port: 3000 }); ``` -------------------------------- ### Install Peer Dependencies Source: https://github.com/event-driven-io/emmett/blob/main/src/docs/frameworks/fastify.md Ensure you have the core Emmett library and Fastify installed as peer dependencies. ```bash npm install @event-driven-io/emmett fastify ``` -------------------------------- ### Install PostgreSQL Event Store Package Source: https://github.com/event-driven-io/emmett/blob/main/src/docs/event-stores/index.md Installs the PostgreSQL event store package for Emmett. ```bash npm install @event-driven-io/emmett-postgresql ``` -------------------------------- ### Install EventStoreDB Event Store Package Source: https://github.com/event-driven-io/emmett/blob/main/src/docs/event-stores/index.md Installs the EventStoreDB event store package for Emmett. ```bash npm install @event-driven-io/emmett-esdb ``` -------------------------------- ### Install Dependencies with Yarn, NPM, or PNPM Source: https://github.com/event-driven-io/emmett/blob/main/src/e2e/esmCompatibility/README.md Use the appropriate command to install project dependencies based on your package manager. ```bash # yarn yarn install # npm npm install # pnpm pnpm install ``` -------------------------------- ### startAPI Source: https://github.com/event-driven-io/emmett/blob/main/src/packages/emmett-fastify/README.md Starts the Fastify server on a specified port. ```APIDOC ## startAPI(app: FastifyInstance, options?: StartApiOptions): Promise ### Description Starts the Fastify server. ### Parameters #### Request Body - **app** (FastifyInstance) - Required - The Fastify application instance. - **options.port** (number) - Optional - Port number to listen on. Defaults to `5000`. ``` -------------------------------- ### Consumer.start Source: https://github.com/event-driven-io/emmett/blob/main/src/packages/emmett-postgresql/README.md Starts the consumer to begin processing events. ```APIDOC ## Consumer.start() ### Description Starts the consumer to begin processing events. ### Returns `Promise` ``` -------------------------------- ### Start from Current Position Source: https://github.com/event-driven-io/emmett/blob/main/src/packages/emmett-esdb/README.md Shows how to start event processing from the current position, useful when checkpoint storage is available. ```APIDOC ## Start from Current Position Use `'CURRENT'` to start processing from where the processor last stopped. This requires checkpoint storage to be configured. ### Usage ```typescript consumer.reactor({ processorId: 'my-processor', startFrom: 'CURRENT', connectionOptions: { database }, // In-memory database for checkpoint storage eachMessage: async (event) => { // Handle event }, }); ``` ``` -------------------------------- ### Install Emmett with bun Source: https://github.com/event-driven-io/emmett/blob/main/src/docs/getting-started.md Add the Emmett package to your project using bun. ```sh $ bun add @event-driven-io/emmett ``` -------------------------------- ### Add start script to package.json Source: https://github.com/event-driven-io/emmett/blob/main/src/docs/quick-intro.md Add a 'start' script to your package.json file to easily run your application using tsx. ```json "start": "tsx ./index.ts" ``` -------------------------------- ### Basic Setup Source: https://github.com/event-driven-io/emmett/blob/main/src/docs/frameworks/fastify.md Set up a basic Fastify application with Emmett, including event store and API definitions. ```APIDOC ## Basic Setup ```typescript import { startAPI, getFastifyApp } from '@event-driven-io/emmett-fastify'; import { getInMemoryEventStore } from '@event-driven-io/emmett'; const eventStore = getInMemoryEventStore(); const app = getFastifyApp({ apis: [shoppingCartApi(eventStore)], }); await startAPI(app, { port: 3000 }); ``` ``` -------------------------------- ### Run Express + PostgreSQL Sample Source: https://github.com/event-driven-io/emmett/blob/main/src/docs/samples/index.md Instructions to clone the repository, set up PostgreSQL using Docker, install dependencies, and run the Express.js application with a PostgreSQL event store. ```bash git clone https://github.com/event-driven-io/emmett.git cd emmett/samples/webApi/expressjs-with-postgresql docker-compose up -d npm install npm run start ``` -------------------------------- ### Complete Shopping Cart WebAPI Definition Source: https://github.com/event-driven-io/emmett/blob/main/src/docs/getting-started.md A comprehensive example of a complete WebAPI setup for a shopping cart, integrating various Emmett features and application logic. ```typescript import { EventStore, InMemoryEventStore, } from "@linked-planet/emmett-core"; import { EmmettExpressApp, handler } from "@linked-planet/emmett-expressjs"; import express from "express"; import { ShoppingCartService } from "../application/shoppingCartService"; import { ProductPriceService } from "../application/productPriceService"; import { shoppingCartApiSetup } from "./shoppingCartApiSetup"; import { shoppingCartEndpointWithOn } from "./shoppingCartEndpointWithOn"; import { createdExample } from "./createdExample"; const app = express(); const eventStore: EventStore = new InMemoryEventStore(); const productPriceService = new ProductPriceService(); const shoppingCartApi = shoppingCartApiSetup(eventStore, productPriceService); const emmettApp = handler(app); shoppingCartApi(emmettApp); shoppingCartEndpointWithOn(shoppingCartService, productPriceService)(emmettApp); createdExample(shoppingCartService)(emmettApp); app.listen(3000, () => { console.log("Server listening on port 3000"); }); ``` -------------------------------- ### Get EventStoreDB Test Client Source: https://github.com/event-driven-io/emmett/blob/main/src/packages/emmett-testcontainers/README.md Use this helper function for simple test setups. It can either use Testcontainers to spin up an EventStoreDB instance or connect to a locally running instance. ```typescript import { getEventStoreDBTestClient } from '@event-driven-io/emmett-testcontainers'; // Use Testcontainers const client = await getEventStoreDBTestClient(true); // Or connect to a local EventStoreDB instance (localhost:2113) const localClient = await getEventStoreDBTestClient(false); ``` -------------------------------- ### Creating Commands with Factory Source: https://github.com/event-driven-io/emmett/blob/main/src/docs/api-reference/command.md Demonstrates how to create command instances using the `command` factory function for runtime creation. ```APIDOC ## Creating Commands with Factory You can either use a regular typescript setup or use the `command` factory function for runtime command creation: ```typescript import { command } from '@event-driven-io/emmett'; const addProduct = command('AddProductItem', { productId: 'shoes-1', quantity: 2, }); // Result: { type: 'AddProductItem', data: {...}, kind: 'Command' } // With timestamp metadata (default) const addProductWithTime = command( 'AddProductItem', { productId: 'shoes-1', quantity: 2 }, { now: new Date() }, ); ``` ``` -------------------------------- ### Evolve Pattern Implementation Example Source: https://github.com/event-driven-io/emmett/blob/main/src/docs/api-reference/projections.md Provides a concrete example of the `evolve` function for a shopping cart projection. It demonstrates how to handle different event types ('ProductItemAdded', 'ShoppingCartConfirmed') to update or delete the document. ```typescript const evolve = (document: CartSummary | null, event: ShoppingCartEvent) => { switch (event.type) { case 'ProductItemAdded': const current = document ?? { totalItems: 0, totalAmount: 0 }; return { ...current, totalItems: current.totalItems + event.data.quantity, }; case 'ShoppingCartConfirmed': return null; // Delete document default: return document; } }; ``` -------------------------------- ### Running Documentation Locally Source: https://github.com/event-driven-io/emmett/blob/main/src/docs/resources/contributing.md Commands to set up and run the documentation development server locally. ```bash cd src/docs npm install npm run dev ``` -------------------------------- ### Complete E2E Test Suite for Web API Source: https://github.com/event-driven-io/emmett/blob/main/src/docs/getting-started.md A complete example of an end-to-end test suite for the Web API, integrating setup, execution, and assertion logic. This demonstrates how to structure comprehensive tests. ```typescript import { ApiE2ETest } from '@event-driven-io/emmett-testcontainers'; const test: ApiE2ETest = ( given: ApiE2ESpecification, ) => ({ client, when, then }) => { // ... test cases ... }; export { test }; ``` -------------------------------- ### Quick Setup EventStoreDB Event Store Source: https://github.com/event-driven-io/emmett/blob/main/src/docs/event-stores/index.md Initializes the EventStoreDB event store using a connection string and the EventStoreDB client. ```typescript import { getEventStoreDBEventStore } from '@event-driven-io/emmett-esdb'; import { EventStoreDBClient } from '@eventstore/db-client'; const client = EventStoreDBClient.connectionString( 'esdb://localhost:2113?tls=false', ); const eventStore = getEventStoreDBEventStore(client); ``` -------------------------------- ### Configure Web API Setup in Emmett Source: https://github.com/event-driven-io/emmett/blob/main/src/docs/getting-started.md Define API routes by providing router configurations to the getApplication method. This example shows setting up a Shopping Carts API with dependencies like an event store and external service calls. ```typescript const app = await getApplication({ apis: [ // Shopping Carts API webApiSetup( '/carts', (router, dependencies) => { router.post('/', createCartHandler(dependencies)); router.post('/:cartId/items', addItemHandler(dependencies)); }, { eventStore: inMemoryEventStore(), getUnitPrice: getUnitPriceStub(), now: () => new Date(), } ), ], }); await startAPI(app); ``` -------------------------------- ### Initialize npm Project Source: https://github.com/event-driven-io/emmett/blob/main/src/docs/quick-intro.md Initialize a new Node.js project using npm. Accepts default settings for simplicity. ```sh npm init ``` -------------------------------- ### Initialize bun Project Source: https://github.com/event-driven-io/emmett/blob/main/src/docs/quick-intro.md Initialize a new Node.js project using bun. Accepts default settings for simplicity. ```sh bun init ``` -------------------------------- ### Default Express.js Application Setup with Emmett Source: https://github.com/event-driven-io/emmett/blob/main/src/docs/frameworks/expressjs.md Use `getApplication` to create an Express.js application with sensible defaults, including JSON body parsing, URL encoding, Problem Details error handling, and ETag support. This provides a quick start for your API. ```typescript const app = getApplication({ apis: [myApi], }); // Includes: // - JSON body parsing // - URL encoding // - Problem Details error handling // - ETag support ``` -------------------------------- ### Basic EventStoreDB Setup Source: https://github.com/event-driven-io/emmett/blob/main/src/docs/event-stores/esdb.md Initialize the EventStoreDB client and create an EventStore instance using the Emmett adapter. Ensure the EventStoreDB server is accessible at the specified connection string. ```typescript import { getEventStoreDBEventStore } from '@event-driven-io/emmett-esdb'; import { EventStoreDBClient } from '@eventstore/db-client'; const client = EventStoreDBClient.connectionString( 'esdb://localhost:2113?tls=false', ); const eventStore = getEventStoreDBEventStore(client); ``` -------------------------------- ### Install Emmett Package Source: https://github.com/event-driven-io/emmett/blob/main/src/packages/emmett/README.md Installs the Emmett library using npm, pnpm, or yarn. Ensure you also install the necessary peer dependencies. ```bash npm install @event-driven-io/emmett # or pnpm add @event-driven-io/emmett # or yarn add @event-driven-io/emmett ``` -------------------------------- ### Install Emmett with MongoDB and Express.js Source: https://github.com/event-driven-io/emmett/blob/main/src/docs/resources/packages.md Installs the core Emmett package, MongoDB integration, and Express.js integration. Also installs testcontainers for development. ```bash npm install @event-driven-io/emmett \ @event-driven-io/emmett-mongodb \ @event-driven-io/emmett-expressjs npm install -D @event-driven-io/emmett-testcontainers ``` -------------------------------- ### Quick Setup In-Memory Event Store Source: https://github.com/event-driven-io/emmett/blob/main/src/docs/event-stores/index.md Initializes the in-memory event store. ```typescript import { getInMemoryEventStore } from '@event-driven-io/emmett'; const eventStore = getInMemoryEventStore(); ``` -------------------------------- ### Install Emmett with EventStoreDB and Fastify Source: https://github.com/event-driven-io/emmett/blob/main/src/docs/resources/packages.md Installs the core Emmett package, EventStoreDB integration, and Fastify integration. Also installs testcontainers for development. ```bash npm install @event-driven-io/emmett \ @event-driven-io/emmett-esdb \ @event-driven-io/emmett-fastify npm install -D @event-driven-io/emmett-testcontainers ``` -------------------------------- ### Install Emmett with PostgreSQL and Express.js Source: https://github.com/event-driven-io/emmett/blob/main/src/docs/resources/packages.md Installs the core Emmett package, PostgreSQL integration, and Express.js integration. Also installs testcontainers for development. ```bash npm install @event-driven-io/emmett \ @event-driven-io/emmett-postgresql \ @event-driven-io/emmett-expressjs npm install -D @event-driven-io/emmett-testcontainers ``` -------------------------------- ### Basic PostgreSQL Event Store Setup Source: https://github.com/event-driven-io/emmett/blob/main/src/docs/event-stores/postgresql.md Initialize the PostgreSQL event store with a connection string. Schema auto-migration is enabled by default. ```typescript import { getPostgreSQLEventStore } from '@event-driven-io/emmett-postgresql'; const eventStore = getPostgreSQLEventStore( 'postgresql://user:password@localhost:5432/mydb', ); // Schema auto-migrates by default ``` -------------------------------- ### Build the Project Source: https://github.com/event-driven-io/emmett/blob/main/CONTRIBUTING.md Compile the project's code. ```shell npm run build ``` -------------------------------- ### Install Emmett MongoDB Adapter Source: https://github.com/event-driven-io/emmett/blob/main/src/packages/emmett-mongodb/README.md Install the package using npm, pnpm, or yarn. Peer dependencies like @event-driven-io/emmett and mongodb must also be installed separately. ```bash npm install @event-driven-io/emmett-mongodb # or pnpm add @event-driven-io/emmett-mongodb # or yarn add @event-driven-io/emmett-mongodb ``` ```bash npm install @event-driven-io/emmett mongodb ``` -------------------------------- ### Configure Application with Pongo and Event Store Source: https://github.com/event-driven-io/emmett/blob/main/src/docs/getting-started.md Initializes the Pongo client and the PostgreSQL event store, then sets up the application with the shopping cart API. Ensure the connection string is correctly provided. ```typescript import { pongoClient } from '@event-driven-io/pongo'; const connectionString = process.env.POSTGRESQL_CONNECTION_STRING ?? 'postgresql://localhost:5432/postgres'; const pongo = pongoClient(connectionString); const eventStore = getPostgreSQLEventStore(connectionString, { projections: projections.inline([ shoppingCartSummaryProjection, clientShoppingSummaryProjection, ]), }); const application = getApplication({ apis: [ shoppingCartApi( eventStore, pongo, // 👈 getUnitPrice, ), ], }); ``` -------------------------------- ### Basic Event Store Setup Source: https://github.com/event-driven-io/emmett/blob/main/src/packages/emmett-postgresql/README.md Set up the PostgreSQL event store using `getPostgreSQLEventStore`. The schema is auto-migrated by default, but manual migration is also supported. ```typescript import { getPostgreSQLEventStore } from '@event-driven-io/emmett-postgresql'; // Create the event store const eventStore = getPostgreSQLEventStore( 'postgresql://user:password@localhost:5432/mydb', ); // Schema is auto-migrated by default // To manually control migration: await eventStore.schema.migrate(); ``` -------------------------------- ### Install Emmett PostgreSQL Adapter Source: https://github.com/event-driven-io/emmett/blob/main/src/packages/emmett-postgresql/README.md Install the PostgreSQL adapter for Emmett using npm, pnpm, or yarn. Ensure peer dependencies like Emmett and Pongo are also installed. ```bash npm install @event-driven-io/emmett-postgresql # or pnpm add @event-driven-io/emmett-postgresql # or yarn add @event-driven-io/emmett-postgresql ``` ```bash npm install @event-driven-io/emmett @event-driven-io/pongo ``` -------------------------------- ### getApplication Source: https://github.com/event-driven-io/emmett/blob/main/src/packages/emmett-fastify/README.md Creates a configured Fastify application instance with specified options for routing, server configuration, and plugins. ```APIDOC ## getApplication(options: ApplicationOptions): Promise ### Description Creates a configured Fastify application instance. ### Parameters #### Request Body - **registerRoutes** (function) - Optional - Function to register your routes - **serverOptions** ({ logger: boolean }) - Optional - Fastify server configuration. Defaults to `{ logger: true }`. - **activeDefaultPlugins** (Plugin[]) - Optional - Plugins to register. Defaults to `[ETag, Compress, FormBody]`. ``` -------------------------------- ### Install Emmett Fastify Package Source: https://github.com/event-driven-io/emmett/blob/main/src/docs/frameworks/fastify.md Install the necessary package for Fastify integration. ```bash npm install @event-driven-io/emmett-fastify ``` -------------------------------- ### Develop Documentation Locally Source: https://github.com/event-driven-io/emmett/blob/main/CONTRIBUTING.md Build and serve the documentation locally using Vitepress. ```shell npm run docs:dev ``` -------------------------------- ### Install Emmett SQLite Package Source: https://github.com/event-driven-io/emmett/blob/main/src/packages/emmett-sqlite/README.md Install the package using npm, pnpm, or yarn. ```bash npm install @event-driven-io/emmett-sqlite # or pnpm add @event-driven-io/emmett-sqlite # or yarn add @event-driven-io/emmett-sqlite ``` -------------------------------- ### PostgreSQL Projection Testing Setup Source: https://github.com/event-driven-io/emmett/blob/main/src/docs/api-reference/projections.md Sets up a PostgreSQL projection for testing using Emmett's `PostgreSQLProjectionSpec`. It requires the projection definition and a connection string, and provides methods to define initial events and expected outcomes. ```typescript import { PostgreSQLProjectionSpec, expectPongoDocuments, eventsInStream, newEventsInStream, } from '@event-driven-io/emmett-postgresql'; describe('Cart Summary Projection', () => { let given: PostgreSQLProjectionSpec; beforeAll(async () => { given = PostgreSQLProjectionSpec.for({ projection: cartSummaryProjection, connectionString: testConnectionString, }); }); it('creates summary on first product', () => given([]) .when([ { type: 'ProductItemAdded', data: { productId: 'shoes', quantity: 2, price: 100 }, metadata: { streamName: 'shopping_cart-123' }, }, ]) .then( expectPongoDocuments .fromCollection('cart_summaries') .withId('123') .toBeEqual({ totalItems: 2, totalAmount: 200 }), )); it('updates summary on additional products', given( eventsInStream('shopping_cart-123', [ { type: 'ProductItemAdded', data: { productId: 'shoes', quantity: 2, price: 100 }, }, ]), ) .when( newEventsInStream('shopping_cart-123', [ { type: 'ProductItemAdded', data: { productId: 'shirt', quantity: 1, price: 50 }, }, ]), ) .then( expectPongoDocuments .fromCollection('cart_summaries') .withId('123') .toBeEqual({ totalItems: 3, totalAmount: 250 }), )); }); ``` -------------------------------- ### Install Peer Dependencies Source: https://github.com/event-driven-io/emmett/blob/main/src/packages/emmett-fastify/README.md Install necessary peer dependencies for Emmett Fastify integration. ```bash npm install @event-driven-io/emmett fastify @fastify/compress @fastify/etag @fastify/formbody close-with-grace ``` -------------------------------- ### Test Express + PostgreSQL Sample Source: https://github.com/event-driven-io/emmett/blob/main/src/docs/samples/index.md Commands to run all tests for the Express.js sample or to use the provided HTTP file for manual API testing with the REST Client extension in VS Code. ```bash # Run all tests npm run test # Or use the HTTP file for manual testing # Open .http file in VS Code with REST Client extension ``` -------------------------------- ### Quick Setup MongoDB Event Store Source: https://github.com/event-driven-io/emmett/blob/main/src/docs/event-stores/index.md Initializes the MongoDB event store using connection details. ```typescript import { getMongoDBEventStore } from '@event-driven-io/emmett-mongodb'; const eventStore = getMongoDBEventStore({ connectionString: 'mongodb://localhost:27017', database: 'events', }); ``` -------------------------------- ### Run Project with Bun Source: https://github.com/event-driven-io/emmett/blob/main/src/e2e/bun/README.md Execute the main project file (index.ts) using the Bun runtime. ```bash bun run index.ts ``` -------------------------------- ### Install Emmett ESDB Package Source: https://github.com/event-driven-io/emmett/blob/main/src/packages/emmett-esdb/README.md Install the EventStoreDB adapter for Emmett along with its peer dependencies. ```bash npm install @event-driven-io/emmett-esdb @event-driven-io/emmett @eventstore/db-client ``` -------------------------------- ### Install Emmett Express.js Package Source: https://github.com/event-driven-io/emmett/blob/main/src/packages/emmett-expressjs/README.md Installs the core package and its peer dependencies for Express.js integration. ```bash npm install @event-driven-io/emmett-expressjs ``` ```bash npm install @event-driven-io/emmett express express-async-errors http-problem-details supertest npm install -D @types/express @types/supertest ``` -------------------------------- ### Install SQLite Event Store Package Source: https://github.com/event-driven-io/emmett/blob/main/src/docs/event-stores/index.md Installs the SQLite event store package for Emmett. ```bash npm install @event-driven-io/emmett-sqlite ``` -------------------------------- ### Install Emmett Express.js Package Source: https://github.com/event-driven-io/emmett/blob/main/src/docs/frameworks/expressjs.md Install the main package for Emmett's Express.js integration. ```bash npm install @event-driven-io/emmett-expressjs ``` -------------------------------- ### Install MongoDB Event Store Package Source: https://github.com/event-driven-io/emmett/blob/main/src/docs/event-stores/index.md Installs the MongoDB event store package for Emmett. ```bash npm install @event-driven-io/emmett-mongodb ``` -------------------------------- ### Shopping Cart API Example Source: https://github.com/event-driven-io/emmett/blob/main/src/packages/emmett-fastify/README.md Demonstrates the decider pattern with Fastify routes for managing a shopping cart. ```APIDOC ## POST /clients/:clientId/shopping-carts ### Description Opens a new shopping cart for a given client. ### Method POST ### Endpoint /clients/:clientId/shopping-carts ### Parameters #### Path Parameters - **clientId** (string) - Required - The ID of the client for whom the cart is opened. ### Request Example (No request body specified in the source) ### Response #### Success Response (201) - **id** (string) - The ID of the newly created shopping cart. #### Response Example ```json { "id": "cartId" } ``` ``` ```APIDOC ## POST /clients/:clientId/shopping-carts/:cartId/items ### Description Adds a product item to a specific shopping cart. ### Method POST ### Endpoint /clients/:clientId/shopping-carts/:cartId/items ### Parameters #### Path Parameters - **clientId** (string) - Required - The ID of the client. - **cartId** (string) - Required - The ID of the shopping cart. #### Request Body - **productId** (string) - Required - The ID of the product to add. - **quantity** (number) - Required - The quantity of the product to add. ### Request Example ```json { "productId": "product123", "quantity": 2 } ``` ### Response #### Success Response (204) No content is returned on success. #### Response Example (No response body specified in the source) ``` ```APIDOC ## POST /clients/:clientId/shopping-carts/:cartId/confirm ### Description Confirms a specific shopping cart, finalizing its state. ### Method POST ### Endpoint /clients/:clientId/shopping-carts/:cartId/confirm ### Parameters #### Path Parameters - **clientId** (string) - Required - The ID of the client. - **cartId** (string) - Required - The ID of the shopping cart to confirm. ### Request Example (No request body specified in the source) ### Response #### Success Response (204) No content is returned on success. #### Response Example (No response body specified in the source) ```