-
Notifications
You must be signed in to change notification settings - Fork 29
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
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
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. |
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(); | ||
``` |
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); | ||
}); | ||
}); |
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; |
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(); |
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", | ||
"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 <[email protected]>", | ||
"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" | ||
} | ||
} |
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
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe 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); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Remove trycatch please. |
||
} | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
{ | ||
"extends": "./tsconfig.json", | ||
"include": [ | ||
"src" | ||
] | ||
} |
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" | ||
] | ||
} |
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, | ||
}, | ||
}); |
There was a problem hiding this comment.
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?