Skip to content

0.12.0

Compare
Choose a tag to compare
@oskardudycz oskardudycz released this 11 Jul 13:06
· 265 commits to main since this release

🚀 What's New

  • Boom! 💣 🔥 🐘 Added a first experimental implementation of PostgreSQL inline projections. by @oskardudycz in #90

You can do it e.g with:

type ShoppingCartShortInfo = {
  productItemsCount: number;
  totalAmount: number;
};

const shoppingCartShortInfoCollectionName = 'shoppingCartShortInfo';

const evolve = (
  document: ShoppingCartShortInfo | null,
  { type, data: event }: ProductItemAdded | DiscountApplied,
): ShoppingCartShortInfo => {
  document = document ?? { productItemsCount: 0, totalAmount: 0 };

  switch (type) {
    case 'ProductItemAdded':
      return {
        totalAmount:
          document.totalAmount +
          event.productItem.price * event.productItem.quantity,
        productItemsCount:
          document.productItemsCount + event.productItem.quantity,
      };
    case 'DiscountApplied':
      return {
        ...document,
        totalAmount: (document.totalAmount * (100 - event.percent)) / 100,
      };
  }
};

const shoppingCartShortInfoProjection = pongoSingleProjection(
  shoppingCartShortInfoCollectionName,
  evolve,
  'ProductItemAdded',
  'DiscountApplied',
);

Then register it as:

import { getPool, getPostgreSQLEventStore } from '@event-driven-io/emmett-postgresql';

const connectionString =
  "postgresql://dbuser:[email protected]:3211/mydb";

const eventStore = getPostgreSQLEventStore(connectionString, {
  projections: [shoppingCartShortInfoProjection],
});

And read models will be updated in the same transaction as appended events.

const shoppingCartId = `shopping_cart-${uuid()}`;
const productItem: PricedProductItem = {
  productId: '123',
  quantity: 10,
  price: 3,
};

await eventStore.appendToStream<ShoppingCartEvent>(shoppingCartId, [
  { type: 'ProductItemAdded', data: { productItem } },
]);

const shoppingCartShortInfo = pongo
  .db()
  .collection<ShoppingCartShortInfo>(shoppingCartShortInfoCollectionName);

const document = await shoppingCartShortInfo.findOne({ _id: shoppingCartId });

📝 What's Changed

  • Added sample showing PostgreSQL event store by @oskardudycz in #87
  • Used code from Dumbo instead of duplicated one between Emmett and Pongo by @oskardudycz in #89

Full Changelog: 0.12.1...0.13.0