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

feat(dynamodb): add dynamodb storage adapter #206

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
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
21 changes: 21 additions & 0 deletions packages/dynamodb/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 Manuel Tarouca

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
77 changes: 77 additions & 0 deletions packages/dynamodb/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
# DynamoDB storage adapter for grammY

Storage adapter that can be used to [store your session data](https://grammy.dev/plugins/session.html) with [AWS DynamoDB](https://aws.amazon.com/dynamodb/) when using sessions.

## Installation

```bash
npm install @grammyjs/storage-dynamodb --save
```

## Usage

You can check the [examples](https://github.com/grammyjs/storages/tree/main/packages/dynamodb/examples) folder, or simply use followed code:

Create a DynamoDB table using [Terraform](https://github.com/hashicorp/terraform):

```hcl
resource "aws_dynamodb_table" "test_table" {
name = "grammy_test_table"
hash_key = "id"
billing_mode = "PAY_PER_REQUEST"
attribute {
name = "id"
type = "S"
}
}
```
> The `id` hash key is required for this adapter to work.
>
> AWS credentials are needed in order to deploy the previous resource.
> It is recommended to store Terraform state in a remote backend.

Deploy resource:

```bash
terraform init
terraform plan
terraform apply
```

Create bot and pass adapter as storage:

```ts
import { Bot, Context, session, SessionFlavor } from "grammy";
import { DynamoDBAdapter } from "@grammyjs/storage-dynamodb";
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";


interface SessionData {
counter: number;
}
type MyContext = Context & SessionFlavor<SessionData>;

const client = new DynamoDBClient();

async function bootstrap() {
const bot = new Bot<MyContext>("");
bot.use(
session({
initial: () => ({ counter: 0 }),
storage: new DynamoDBAdapter<SessionData>({
tableName: "grammy_test_table",
dynamoDbClient: client
}),
})
);

bot.command("stats", (ctx) =>
ctx.reply(`Already got ${ctx.session.counter} photos!`)
);
bot.on(":photo", (ctx) => ctx.session.counter++);

bot.start();
}

bootstrap();
```
71 changes: 71 additions & 0 deletions packages/dynamodb/__tests__/dynamodb-test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { session } from 'grammy';
import { DynamoDBAdapter } from '../src';
import { test, expect, describe, beforeEach } from 'vitest';
import { createBot, createMessage } from '@grammyjs/storage-utils';
import { DynamoDBClient, GetItemCommand } from '@aws-sdk/client-dynamodb';
import dynamodb from './helpers/dynamodb';
import { mockClient } from 'aws-sdk-client-mock';

describe('Pizza counter test', () => {
const ddbMock = mockClient(DynamoDBClient);

beforeEach(() => {
ddbMock.reset();
});

const adapter = new DynamoDBAdapter({
tableName: 'grammy_test_table',
dynamoDbClient: dynamodb,
});

test('Pizza counter should be equals 0 on initial', async () => {
const bot = createBot();
const firstMessage = createMessage(bot);

ddbMock.resolves({});

bot.use(
session<any, any>({
initial: () => ({ pizzaCount: 0 }),
storage: adapter,
}),
);
bot.on('msg:text', (ctx) => {
expect(ctx.session.pizzaCount).toEqual(0);
});

await bot.handleUpdate(firstMessage.update);
});

test('Pizza counter should be equals 1 after first message', async () => {
const bot = createBot();

bot.use(
session<any, any>({
initial: () => ({ pizzaCount: 0 }),
storage: new DynamoDBAdapter({
tableName: 'grammy_test_table',
dynamoDbClient: dynamodb,
}),
})
);
bot.hears('first', (ctx) => {
ctx.session.pizzaCount = Number(ctx.session.pizzaCount) + 1;
});

bot.hears('second', (ctx) => {
expect(ctx.session.pizzaCount).toEqual(1);
ctx.session.pizzaCount = Number(ctx.session.pizzaCount) + 1;
});

const firstMessage = createMessage(bot, 'first');
const secondMessage = createMessage(bot, 'second');

ddbMock.resolves({}).on(GetItemCommand)
.resolvesOnce({ Item: { id: { S: '1' }, Value: { S: '{"pizzaCount":0}' } } })
.resolvesOnce({ Item: { id: { S: '1' }, Value: { S: '{"pizzaCount":1}' } } });

await bot.handleUpdate(firstMessage.update);
await bot.handleUpdate(secondMessage.update);
});
});
4 changes: 4 additions & 0 deletions packages/dynamodb/__tests__/helpers/dynamodb.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { DynamoDBClient } from '@aws-sdk/client-dynamodb';

const dynamodb = new DynamoDBClient();
export default dynamodb;
33 changes: 33 additions & 0 deletions packages/dynamodb/examples/node.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { Bot, Context, session, SessionFlavor } from "grammy";
import { DynamoDBAdapter } from "@grammyjs/storage-dynamodb";
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";


interface SessionData {
counter: number;
}
type MyContext = Context & SessionFlavor<SessionData>;

const client = new DynamoDBClient();

async function bootstrap() {
const bot = new Bot<MyContext>("");
bot.use(
session({
initial: () => ({ counter: 0 }),
storage: new DynamoDBAdapter<SessionData>({
tableName: "grammy_test_table",
dynamoDbClient: client
}),
})
);

bot.command("stats", (ctx) =>
ctx.reply(`Already got ${ctx.session.counter} photos!`)
);
bot.on(":photo", (ctx) => ctx.session.counter++);

bot.start();
}

bootstrap();
51 changes: 51 additions & 0 deletions packages/dynamodb/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
{
"name": "@grammyjs/storage-dynamodb",
"version": "2.4.0",
"description": "AWS DynamoDB storage adapter for grammY",
"types": "dist/index.d.ts",
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think main field missed there?

"files": [
"README.md",
"dist",
"package.json",
"LICENSE"
],
"scripts": {
"test:deno": "echo \"Error: no tests found\"",
"test": "vitest",
"start": "node dist/index.js",
"dev": "nodemon",
"debug": "node --inspect=0.0.0.0:9229 --nolazy ./dist/index.js",
"prebuild": "rimraf dist",
"build": "tsc -p tsconfig.build.json",
"changelog": "conventional-changelog -p angular -i CHANGELOG.md -s --commit-path ."
},
"repository": {
"type": "git",
"url": "git+https://github.com/grammyjs/storages.git"
},
"author": "mt <manue+git@matm.xyz>",
"license": "MIT",
"bugs": {
"url": "https://github.com/grammyjs/storages/issues"
},
"homepage": "https://github.com/grammyjs/storages#readme",
"keywords": [
"grammy",
"telegram",
"bot",
"session",
"storage",
"adapter",
"middleware",
"aws",
"dynamodb"
],
"devDependencies": {
"@aws-sdk/client-dynamodb": "^3.433.0",
"@grammyjs/storage-utils": "^2.4.0",
"aws-sdk-client-mock": "^3.0.0",
"grammy": "^1.19.2",
"vite": "^4.5.0",
"vitest": "^0.34.6"
}
}
67 changes: 67 additions & 0 deletions packages/dynamodb/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import { StorageAdapter } from 'grammy';
import { DynamoDBClient, PutItemCommand, GetItemCommand, DeleteItemCommand } from '@aws-sdk/client-dynamodb';

export interface DynamoDBAdapterOptions {
tableName: string;
dynamoDbClient: DynamoDBClient
}

export class DynamoDBAdapter<T> implements StorageAdapter<T> {
private client: DynamoDBClient;
private tableName: string;

constructor(options: DynamoDBAdapterOptions) {
this.client = options.dynamoDbClient;
this.tableName = options.tableName;
}

async read(key: string) {
const getItemCommand = new GetItemCommand({
TableName: this.tableName,
Key: {
id: { S: key },
},
});

try {
const response = await this.client.send(getItemCommand);
const item = response.Item;
if (item) {
return JSON.parse(item.Value.S) as T;
}
Comment on lines +29 to +31
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You should response with null in case item not found.

} catch (error) {
console.error('Error reading item from DynamoDB:', error);
}
Comment on lines +32 to +34
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess we shouldn't catch something there and especially logging.

}

async write(key: string, data: T) {
const putItemCommand = new PutItemCommand({
TableName: this.tableName,
Item: {
id: { S: key },
Value: { S: JSON.stringify(data) },
},
});

try {
await this.client.send(putItemCommand);
} catch (error) {
console.error('Error writing item to DynamoDB:', error);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove trycatch please.

}
}

async delete(key: string) {
const deleteItemCommand = new DeleteItemCommand({
TableName: this.tableName,
Key: {
id: { S: key },
},
});

try {
await this.client.send(deleteItemCommand);
} catch (error) {
console.error('Error deleting item from DynamoDB:', error);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remove trycatch please.

}
}
}
6 changes: 6 additions & 0 deletions packages/dynamodb/tsconfig.build.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"extends": "./tsconfig.json",
"include": [
"src"
]
}
24 changes: 24 additions & 0 deletions packages/dynamodb/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"compilerOptions": {
"moduleResolution": "node",
"target": "ES2019",
"lib": [
"ES2019"
],
"module": "CommonJS",
"declaration": true,
"outDir": "./dist",
"strict": false,
"esModuleInterop": true,
"inlineSourceMap": true,
"skipLibCheck": true,
},
"include": [
"src",
"__tests__",
"examples"
],
"exclude": [
"node_modules"
]
}
10 changes: 10 additions & 0 deletions packages/dynamodb/vitest.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { defineConfig } from 'vitest/config';

export default defineConfig({
test: {
include: ['__tests__/*.ts'],
exclude: ['__tests__/helpers'],
watch: false,
threads: false,
},
});
Loading
Loading