npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

funamots

v3.5.0

Published

Functional typescript DynamoDB Client

Downloads

2,879

Readme

Typesafe Dynamo DB Client for Typescript.

Why?

DynamoDB has some non trivial data modelling & querying rules. This library expresses those rules as typescript types.

This library leans on some type level programming to stop mistakes at compile time that normally arent caught until runtime.

e.g. The compiler will whinge at you if you try and

  • get with non key attributes
  • query by non key attributes
  • put an item missing key attributes
  • get/query/put with key attributes whos types do not match the configured table

The syntax is also much friendlier than the vanilla AWS DynamoDB client.

Detailed Docs

See here: ./docs/index.md

Supported Operations

  • Get/Put/Query
  • BatchX
  • TransactX
  • Scan

How?

Basic Usage - Hash Key Only

type SimpleKey = {
  readonly hash: string;
  readonly map?: {
    readonly name: string;
  };
};

const simpleTable = tableBuilder<SimpleKey>('MySimpleTable')
  .withKey('hash')
  .build();

const value = { hash: '1' };
await simpleTable.put(value);
const result = await simpleTable.get(value);
expect(result).toEqual(value);

Basic Usage - Hash & Sort Key

type CompoundKey = {
  readonly hash: string;
  readonly sort: number;
};

const compoundTable = tableBuilder<CompoundKey>('MyCompoundTable')
  .withKey('hash', 'sort')
  .build();

const key = { hash: '1', sort: 1 };
await compoundTable.put(key);
const result = await compoundTable.get(key);
expect(result?.hash).toEqual(key.hash);
expect(result?.sort).toEqual(key.sort);

Hash & Sort Key, GSIs and LSIs

type CompoundKey = {
  readonly hash: string;
  readonly sort: number;
  readonly gsiHash: string;
  readonly gsiSort: string;
  readonly lsiSort: string;
};

const compoundTable = tableBuilder<CompoundKey>('MyCompoundTable')
  .withKey('hash', 'sort')
  .withGlobalIndex('ix_by_gsihash', 'gsiHash', 'gsiSort')
  .withLocalIndex('ix_by_lsirange', 'lsiSort')
  .build();

const testObjects = Array.from(Array(20).keys()).map((i) => ({
  hash: '1',
  sort: i,
  gsihash: 'hash value',
  gsirange: `${100 - i}`,
  lsirange: 1,
}));

await compoundTable.transactPut((doc) => { return { item: doc } }));
const result = await compoundTable.indexes.ix_by_gsihash.query('hash value');
expect(result.records.length).toEqual(testObjects.length);

const testLocalObjects = Array.from(Array(20).keys()).map((i) => ({
  hash: '1',
  sort: i,
  lsirange: 20 - i,
}));
await compoundTable.batchPut(testLocalObjects);
const result = await compoundTable.indexes.ix_by_lsirange.query('1', {
  sortKeyExpression: { '>': 5 },
});

"Real world" Repository Pattern

type Order = {
  readonly orderId: string;
  readonly orderDate: string;
  readonly customerId: string;
  readonly products: string[];
  readonly totalPrice: number;
  readonly documentVersion: string;
};

const OrdersRepo = (client: DynamoDB) => {
  type OrderDto = {
    readonly hash: string;
    readonly range: 'ORDER';
    readonly customerIxHash: string;
    readonly dateSort: string;
    readonly dailyOrdersIxHash: string;
    readonly documentVersion?: string;
    readonly order: Order;
  };

  const table = tableBuilder<OrderDto>('Orders')
    .withKey('hash', 'range')
    .withGlobalIndex('ordersByCustomer', 'customerIxHash', 'dateSort')
    .withGlobalIndex('dailyOrders', 'dailyOrdersIxHash', 'dateSort')
    .build({ client });

  const dateToDay = (isoDate: string) => {
    const date = new Date(isoDate);
    return `${date.getUTCFullYear()}${date.getUTCMonth()}${date.getUTCDay()}`;
  };

  const mapToDto = (o: Order): OrderDto => ({
    hash: o.orderId,
    range: 'ORDER',
    customerIxHash: o.customerId,
    dateSort: `${o.orderDate}:${o.orderId}`,
    dailyOrdersIxHash: dateToDay(o.orderDate),
    documentVersion: o.documentVersion || uuid(),
    order: o,
  });

  return {
    saveOrder: (o: Order) =>
      table.put(mapToDto(o), {
        conditionExpression: OR<CompoundKey>(
          {
            documentVersionId: attributeNotExists(),
          },
          {
            documentVersionId: { '=': o.documentVersion },
          }
        ),
      }),
    getOrder: (orderId: string) =>
      table.get({ hash: orderId, range: 'ORDER' }).then((r) => r?.order),
    getCustomerOrdersSince: (customerId: string, sinceIsoDate: string) =>
      table.indexes.ordersByCustomer
        .query(customerId, {
          sortKeyExpression: { '>': sinceIsoDate },
        })
        .then((r) => r.records.map((r) => r.order)),
    listTodaysOrders: (nextPageKey?: string) =>
      table.indexes.dailyOrders
        .query(dateToDay(new Date().toISOString()), {
          fromSortKey: nextPageKey,
        })
        .then((r) => ({
          nextPageKey: r.lastSortKey,
          orders: r.records.map((r) => r.order),
        })),
  };
};

Use

npm install funamots or yarn add funamots

Develop

pnpm test uses jest-dynamodb to run a local dynamodb instance.