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

@initd.sg/dynamodb-service

v1.0.0

Published

An abstract dynamodb service data layer.

Downloads

70

Readme

DynamoDB Service Package

A TypeScript-friendly wrapper for AWS DynamoDB that simplifies common database operations with type safety and clean abstractions.

Features

  • Type-safe operations with TypeScript generics
  • Simplified CRUD operations
  • Batch operations support
  • Query and Scan operations with filters
  • Support for tables with composite keys (hash + range)
  • Index querying support
  • Automatic batch processing for large operations

Installation

yarn add @initd.sg/dynamodb-service

Usage

Creating a Service

Create a service by extending the AbstractService class:

interface User {
    userId: string;
    email: string;
    name: string;
    createdAt: number;
}

class UserService extends AbstractService<User> {
    tableName = "Users";

    save(user: User) {
        await userService._save({
            hashKey: "userId",
            obj: user,
        });
    }

    get(id: string) {
        return this._get({
            hashKey: "userId",
            hashKeyValue: "123"
        })
    }

    getWithRange(id: string, createAt: number) {
        return this._get({
            hashKey: "userId",
            hashKeyValue: id,
            rangeKey: "createdAt",
            rangeKeyValue: createdAt,
        })
    }

    query(opt: GetOptions) {
        return this._query(opts);
    }

    queryBetween(opt: GetOptions & { rangeKeyStartValue: number, rangeKeyEndValue: number }) {
        return this._queryBetween(opts);
    }

    batchGet(items: BatchGetOptions) {
        return this._batchGet(items);
    }

    list(opts: ListOptions) {
        return this._list(opts);
    }

    delete(id: string) {
        return this._delete({
            hashKey: "userId",
            hashKeyValue: id
        });
    }

    paginate(opts: PaginateOptions) {
        return this._paginate(opts);
    }
}

Basic Operations

Save an Item

const userService = new UserService();

await userService.save({
    userId: "123",
    email: "[email protected]",
    name: "John Doe",
    createdAt: Date.now()
});

Get an Item

// Get by hash key
const user = await userService.get("123");

// Get by hash key and range key
const user = await userService.getWithRange("123", 1234567890);

Query Items

// Basic query
const users = await userService.query({
    hashKey: "userId",
    hashKeyValue: "123"
});

// Query with index
const users = await userService.query({
    index: "email-index",
    hashKey: "email",
    hashKeyValue: "[email protected]"
});

// Query with ordering and limit
const users = await userService.query({
    hashKey: "userId",
    hashKeyValue: "123",
    order: "dsc",
    limit: 10
});

Query Between Range Values

const users = await userService.queryBetween({
    hashKey: "userId",
    hashKeyValue: "123",
    rangeKey: "createdAt",
    rangeKeyStartValue: 1234567890,
    rangeKeyEndValue: 1234567899
});

Batch Get Items

const users = await userService.batchGet({
    items: [
        { hashKey: "userId", hashKeyValue: "123" },
        { hashKey: "userId", hashKeyValue: "456" }
    ]
});

List Items

// Get all items
const allUsers = await userService.getAll();

// List with filters
const filteredUsers = await userService.list({
    filters: {
        status: "active"
    },
    limit: 10
});

Delete an Item

await userService.delete("userId");

Paginate Items

// fetch first page
const { items, lastEvaluatedKeys } = await userService.paginate({
    limit: 10,
});

// fetch the next page
await userService.paginate({
    limit: 10,
    lastEvaluatedKeys,
});

Configuration

You can provide your own DynamoDB client instance:

const customClient = new DynamoDBClient({
    region: 'us-east-1',
    credentials: {
        accessKeyId: 'YOUR_ACCESS_KEY',
        secretAccessKey: 'YOUR_SECRET_KEY'
    }
});

const userService = new UserService({ dynamoDBClient: customClient });

API Reference

AbstractService

Base class that provides all DynamoDB operations. Generic type T represents the shape of your table items.

Methods

  • _save(options: SaveOptions<T>): Promise<T>
  • _get(options: GetOptions<T>): Promise<T | null>
  • _query(options: GetOptions<T>): Promise<T[]>
  • _queryBetween(options: GetOptions<T> & {rangeKeyStartValue, rangeKeyEndValue}): Promise<T[]>
  • _batchGet(options: BatchGetOptions<T>): Promise<T[]>
  • _list(options: ListOptions): Promise<T[]>
  • getAll(): Promise<T[]>
  • _delete(options: DeleteOptions<H, R>): Promise<void>
  • _paginate(options: PaginateOptions): Promise<{ items: T[], lastEvaluatedKey: Record<string, any> }>

License

MIT

Related article

https://medium.com/@initd.sg/dynamodb-made-easy-simplifying-dynamodb-interactions-using-initd-sg-dynamodb-service-0a53a1a00c3c