Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added Express.js HTTP handler #17

Merged
merged 3 commits into from
Feb 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
"files.exclude": {
"node_modules/": true,
"**/node_modules/": true,
"**/dist/": true
"**/dist/": true,
"**/*.tsbuildinfo": true
},
"files.eol": "\n",

Expand Down
4 changes: 2 additions & 2 deletions docs/snippets/gettingStarted/businessLogic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,14 +14,14 @@ import type {
import type { ShoppingCart } from './state';

// #region getting-started-business-logic
import { sum } from '@event-driven-io/emmett';
import { sum, ValidationError } from '@event-driven-io/emmett';

const addProductItem = (
command: AddProductItemToShoppingCart,
state: ShoppingCart,
): ProductItemAddedToShoppingCart => {
if (state.status === 'Closed')
throw new Error('Shopping Cart already closed');
throw new ValidationError('Shopping Cart already closed');

const {
data: { shoppingCartId, productItem },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,40 +6,29 @@ import {
assertUnsignedBigInt,
type EventStore,
} from '@event-driven-io/emmett';
import type { Request, Response, Router } from 'express';
import { sendCreated } from '..';
import { type Request, type Router } from 'express';
import {
getETagFromIfMatch,
getWeakETagValue,
setETag,
Created,
NoContent,
getETagValueFromIfMatch,
on,
toWeakETag,
} from '../etag';
} from '../../';
import { decider } from './businessLogic';
import { type PricedProductItem, type ProductItem } from './shoppingCart';

export const mapShoppingCartStreamId = (id: string) => `shopping_cart-${id}`;

export const handle = DeciderCommandHandler(decider, mapShoppingCartStreamId);
export const handle = DeciderCommandHandler(decider);

const dummyPriceProvider = (_productId: string) => {
return 100;
};

export const getExpectedStreamVersion = (request: Request): bigint => {
const eTag = getETagFromIfMatch(request);
const weakEtag = getWeakETagValue(eTag);

return assertUnsignedBigInt(weakEtag);
};

export const shoppingCartApi = (eventStore: EventStore) => (router: Router) => {
// Open Shopping cart
router.post(
'/clients/:clientId/shopping-carts/',
async (request: Request, response: Response) => {
on(async (request: Request) => {
const clientId = assertNotEmptyString(request.params.clientId);
// We're using here clientId as a shopping cart id (instead a random uuid) to make it unique per client.
// What potential issue do you see in that?
const shoppingCartId = clientId;

const result = await handle(
Expand All @@ -52,14 +41,16 @@ export const shoppingCartApi = (eventStore: EventStore) => (router: Router) => {
{ expectedStreamVersion: STREAM_DOES_NOT_EXIST },
);

setETag(response, toWeakETag(result.nextExpectedStreamVersion));
sendCreated(response, shoppingCartId);
},
return Created({
createdId: shoppingCartId,
eTag: toWeakETag(result.nextExpectedStreamVersion),
});
}),
);

router.post(
'/clients/:clientId/shopping-carts/:shoppingCartId/product-items',
async (request: AddProductItemRequest, response: Response) => {
on(async (request: AddProductItemRequest) => {
const shoppingCartId = assertNotEmptyString(
request.params.shoppingCartId,
);
Expand All @@ -79,18 +70,21 @@ export const shoppingCartApi = (eventStore: EventStore) => (router: Router) => {
productItem: { ...productItem, unitPrice },
},
},
{ expectedStreamVersion: getExpectedStreamVersion(request) },
{
expectedStreamVersion: assertUnsignedBigInt(
getETagValueFromIfMatch(request),
),
},
);

setETag(response, toWeakETag(result.nextExpectedStreamVersion));
response.sendStatus(204);
},
return NoContent({ eTag: toWeakETag(result.nextExpectedStreamVersion) });
}),
);

// Remove Product Item
router.delete(
'/clients/:clientId/shopping-carts/:shoppingCartId/product-items',
async (request: Request, response: Response) => {
on(async (request: Request) => {
const shoppingCartId = assertNotEmptyString(
request.params.shoppingCartId,
);
Expand All @@ -107,18 +101,21 @@ export const shoppingCartApi = (eventStore: EventStore) => (router: Router) => {
type: 'RemoveProductItemFromShoppingCart',
data: { shoppingCartId, productItem },
},
{ expectedStreamVersion: getExpectedStreamVersion(request) },
{
expectedStreamVersion: assertUnsignedBigInt(
getETagValueFromIfMatch(request),
),
},
);

setETag(response, toWeakETag(result.nextExpectedStreamVersion));
response.sendStatus(204);
},
return NoContent({ eTag: toWeakETag(result.nextExpectedStreamVersion) });
}),
);

// Confirm Shopping Cart
router.post(
'/clients/:clientId/shopping-carts/:shoppingCartId/confirm',
async (request: Request, response: Response) => {
on(async (request: Request) => {
const shoppingCartId = assertNotEmptyString(
request.params.shoppingCartId,
);
Expand All @@ -130,18 +127,21 @@ export const shoppingCartApi = (eventStore: EventStore) => (router: Router) => {
type: 'ConfirmShoppingCart',
data: { shoppingCartId, now: new Date() },
},
{ expectedStreamVersion: getExpectedStreamVersion(request) },
{
expectedStreamVersion: assertUnsignedBigInt(
getETagValueFromIfMatch(request),
),
},
);

setETag(response, toWeakETag(result.nextExpectedStreamVersion));
response.sendStatus(204);
},
return NoContent({ eTag: toWeakETag(result.nextExpectedStreamVersion) });
}),
);

// Cancel Shopping Cart
router.delete(
'/clients/:clientId/shopping-carts/:shoppingCartId',
async (request: Request, response: Response) => {
on(async (request: Request) => {
const shoppingCartId = assertNotEmptyString(
request.params.shoppingCartId,
);
Expand All @@ -153,12 +153,15 @@ export const shoppingCartApi = (eventStore: EventStore) => (router: Router) => {
type: 'CancelShoppingCart',
data: { shoppingCartId, now: new Date() },
},
{ expectedStreamVersion: getExpectedStreamVersion(request) },
{
expectedStreamVersion: assertUnsignedBigInt(
getETagValueFromIfMatch(request),
),
},
);

setETag(response, toWeakETag(result.nextExpectedStreamVersion));
response.sendStatus(204);
},
return NoContent({ eTag: toWeakETag(result.nextExpectedStreamVersion) });
}),
);
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,17 +9,17 @@ import assert from 'node:assert/strict';
import { beforeEach, describe, it } from 'node:test';
import request from 'supertest';
import { v4 as uuid } from 'uuid';
import { getApplication } from '..';
import { HeaderNames, toWeakETag } from '../etag';
import { mapShoppingCartStreamId, shoppingCartApi } from './api';
import { ShoppingCartErrors } from './businessLogic';
import type { ShoppingCartEvent } from './shoppingCart';
import { getApplication } from '../..';
import { HeaderNames, toWeakETag } from '../../etag';
import {
expectNextRevisionInResponseEtag,
runTwice,
statuses,
type TestResponse,
} from './testing';
} from '../testing';
import { shoppingCartApi } from './api';
import { ShoppingCartErrors } from './businessLogic';
import type { ShoppingCartEvent } from './shoppingCart';

describe('Application logic with optimistic concurrency', () => {
let app: Application;
Expand Down Expand Up @@ -124,15 +124,14 @@ describe('Application logic with optimistic concurrency', () => {
.delete(`/clients/${clientId}/shopping-carts/${shoppingCartId}`)
.set(HeaderNames.IF_MATCH, toWeakETag(currentRevision))
.expect((response) => {
assert.equal(response.statusCode, 500);
assert.equal(response.statusCode, 403);
assertMatches(response.body, {
detail: ShoppingCartErrors.CART_IS_ALREADY_CLOSED,
});
});

const result = await eventStore.readStream<ShoppingCartEvent>(
mapShoppingCartStreamId(shoppingCartId),
);
const result =
await eventStore.readStream<ShoppingCartEvent>(shoppingCartId);

assert.ok(result);
assert.equal(result.events.length, Number(currentRevision));
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
import type { Decider } from '@event-driven-io/emmett';
import {
EmmettError,
IllegalStateError,
type Decider,
} from '@event-driven-io/emmett';

import {
ShoppingCartStatus,
Expand Down Expand Up @@ -84,7 +88,7 @@ export const assertProductItemExists = (
)?.quantity ?? 0;

if (currentQuantity < quantity) {
throw new Error(ShoppingCartErrors.PRODUCT_ITEM_NOT_FOUND);
throw new IllegalStateError(ShoppingCartErrors.PRODUCT_ITEM_NOT_FOUND);
}
};

Expand All @@ -95,7 +99,7 @@ export const decide = (
switch (type) {
case 'OpenShoppingCart': {
if (shoppingCart.status !== ShoppingCartStatus.Empty) {
throw new Error(ShoppingCartErrors.CART_ALREADY_EXISTS);
throw new IllegalStateError(ShoppingCartErrors.CART_ALREADY_EXISTS);
}
return {
type: 'ShoppingCartOpened',
Expand All @@ -109,7 +113,7 @@ export const decide = (

case 'AddProductItemToShoppingCart': {
if (shoppingCart.status !== ShoppingCartStatus.Pending) {
throw new Error(ShoppingCartErrors.CART_IS_ALREADY_CLOSED);
throw new IllegalStateError(ShoppingCartErrors.CART_IS_ALREADY_CLOSED);
}
return {
type: 'ProductItemAddedToShoppingCart',
Expand All @@ -122,7 +126,7 @@ export const decide = (

case 'RemoveProductItemFromShoppingCart': {
if (shoppingCart.status !== ShoppingCartStatus.Pending) {
throw new Error(ShoppingCartErrors.CART_IS_ALREADY_CLOSED);
throw new IllegalStateError(ShoppingCartErrors.CART_IS_ALREADY_CLOSED);
}

assertProductItemExists(shoppingCart.productItems, command.productItem);
Expand All @@ -138,11 +142,11 @@ export const decide = (

case 'ConfirmShoppingCart': {
if (shoppingCart.status !== ShoppingCartStatus.Pending) {
throw new Error(ShoppingCartErrors.CART_IS_ALREADY_CLOSED);
throw new IllegalStateError(ShoppingCartErrors.CART_IS_ALREADY_CLOSED);
}

if (shoppingCart.productItems.length === 0) {
throw new Error(ShoppingCartErrors.CART_IS_EMPTY);
throw new IllegalStateError(ShoppingCartErrors.CART_IS_EMPTY);
}

return {
Expand All @@ -156,7 +160,7 @@ export const decide = (

case 'CancelShoppingCart': {
if (shoppingCart.status !== ShoppingCartStatus.Pending) {
throw new Error(ShoppingCartErrors.CART_IS_ALREADY_CLOSED);
throw new IllegalStateError(ShoppingCartErrors.CART_IS_ALREADY_CLOSED);
}

return {
Expand All @@ -169,7 +173,7 @@ export const decide = (
}
default: {
const _: never = command;
throw new Error(ShoppingCartErrors.UNKNOWN_COMMAND_TYPE);
throw new EmmettError(ShoppingCartErrors.UNKNOWN_COMMAND_TYPE);
}
}
};
Expand Down
12 changes: 11 additions & 1 deletion packages/emmett-expressjs/src/etag.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Brand } from '@event-driven-io/emmett';
import { type Brand } from '@event-driven-io/emmett';
import type { Request, Response } from 'express';

//////////////////////////////////////
Expand Down Expand Up @@ -61,3 +61,13 @@ export const getETagFromIfNotMatch = (request: Request): ETag => {
export const setETag = (response: Response, etag: ETag): void => {
response.setHeader(HeaderNames.ETag, etag as string);
};

export const getETagValueFromIfMatch = (request: Request): string => {
// TODO: https://github.com/event-driven-io/emmett/issues/18
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const eTagValue: ETag = getETagFromIfMatch(request);

return isWeakETag(eTagValue)
? getWeakETagValue(eTagValue)
: (eTagValue as string);
};
Loading