@keyv/dynamo 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2017-2021 Luke Childs
4
+ Copyright (c) 2021-2022 Jared Wray
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,40 @@
1
+ # @keyv/dynamo [<img width="100" align="right" src="https://jaredwray.com/images/keyv-symbol.svg" alt="keyv">](https://github.com/jaredwra/keyv)
2
+
3
+ > DynamoDB storage adapter for Keyv
4
+
5
+ [![build](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml/badge.svg)](https://github.com/jaredwray/keyv/actions/workflows/tests.yaml)
6
+ [![codecov](https://codecov.io/gh/jaredwray/keyv/branch/main/graph/badge.svg?token=bRzR3RyOXZ)](https://codecov.io/gh/jaredwray/keyv)
7
+ [![npm](https://img.shields.io/npm/v/@keyv/dynamo.svg)](https://www.npmjs.com/package/@keyv/dynamo)
8
+ [![npm](https://img.shields.io/npm/dm/@keyv/dynamo)](https://npmjs.com/package/@keyv/dynamo)
9
+
10
+ DynamoDB storage adapter for [Keyv](https://github.com/jaredwray/keyv).
11
+
12
+ Uses TTL indexes to automatically remove expired documents. However [DynamoDB doesn't guarantee data will be deleted immediately upon expiration](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/TTL.html).
13
+
14
+ ## Install
15
+
16
+ ```shell
17
+ npm install --save keyv @keyv/dynamo
18
+ ```
19
+
20
+ ## Usage
21
+
22
+ ```js
23
+ import Keyv from 'keyv';
24
+ import KeyvDynamo from '@keyv/dynamo';
25
+
26
+ const keyv = new Keyv(new KeyvDynamo());
27
+ keyv.on('error', handleConnectionError);
28
+ ```
29
+
30
+ You can specify the table name, by default `'keyv'` is used.
31
+
32
+ e.g:
33
+
34
+ ```js
35
+ const keyv = new KeyvDynamo({ tableName: 'cacheTable' });
36
+ ```
37
+
38
+ ## License
39
+
40
+ [MIT © Jared Wray](LISCENCE)
package/dist/index.cjs ADDED
@@ -0,0 +1,150 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ KeyvDynamo: () => KeyvDynamo,
34
+ default: () => index_default
35
+ });
36
+ module.exports = __toCommonJS(index_exports);
37
+ var import_events = __toESM(require("events"), 1);
38
+ var import_client_dynamodb = require("@aws-sdk/client-dynamodb");
39
+ var import_lib_dynamodb = require("@aws-sdk/lib-dynamodb");
40
+ var KeyvDynamo = class extends import_events.default {
41
+ ttlSupport = true;
42
+ sixHoursInMilliseconds = 6 * 60 * 60 * 1e3;
43
+ namespace;
44
+ opts;
45
+ client;
46
+ constructor(options) {
47
+ super();
48
+ options ??= {};
49
+ if (typeof options === "string") {
50
+ options = { endpoint: options };
51
+ }
52
+ this.opts = {
53
+ tableName: "keyv",
54
+ dialect: "dynamo",
55
+ ...options
56
+ };
57
+ this.client = import_lib_dynamodb.DynamoDBDocument.from(new import_client_dynamodb.DynamoDB(this.opts));
58
+ this.checkTableExists(this.opts.tableName).catch((error) => {
59
+ this.emit("error", error);
60
+ });
61
+ }
62
+ async checkTableExists(tableName) {
63
+ await this.client.send(new import_client_dynamodb.DescribeTableCommand({ TableName: tableName }));
64
+ }
65
+ async set(key, value, ttl) {
66
+ const sixHoursFromNowEpoch = Math.floor((Date.now() + this.sixHoursInMilliseconds) / 1e3);
67
+ const expiresAt = typeof ttl === "number" ? Math.floor((Date.now() + (ttl + 1e3)) / 1e3) : sixHoursFromNowEpoch;
68
+ const putInput = {
69
+ TableName: this.opts.tableName,
70
+ Item: {
71
+ id: key,
72
+ value,
73
+ expiresAt
74
+ }
75
+ };
76
+ await this.client.put(putInput);
77
+ }
78
+ async get(key) {
79
+ const getInput = {
80
+ TableName: this.opts.tableName,
81
+ Key: {
82
+ id: key
83
+ }
84
+ };
85
+ const { Item } = await this.client.get(getInput);
86
+ return Item?.value;
87
+ }
88
+ async delete(key) {
89
+ const deleteInput = {
90
+ TableName: this.opts.tableName,
91
+ Key: {
92
+ id: key
93
+ },
94
+ ReturnValues: "ALL_OLD"
95
+ };
96
+ const { Attributes } = await this.client.delete(deleteInput);
97
+ return Boolean(Attributes);
98
+ }
99
+ async getMany(keys) {
100
+ const batchGetInput = {
101
+ RequestItems: {
102
+ [this.opts.tableName]: {
103
+ Keys: keys.map((key) => ({
104
+ id: key
105
+ }))
106
+ }
107
+ }
108
+ };
109
+ const { Responses: { [this.opts.tableName]: items = [] } = {} } = await this.client.batchGet(batchGetInput);
110
+ return keys.map((key) => items.find((item) => item?.id === key)?.value);
111
+ }
112
+ async deleteMany(keys) {
113
+ if (keys.length === 0) {
114
+ return false;
115
+ }
116
+ const items = await this.getMany(keys);
117
+ if (items.filter(Boolean).length === 0) {
118
+ return false;
119
+ }
120
+ const batchDeleteInput = {
121
+ RequestItems: {
122
+ [this.opts.tableName]: keys.map((key) => ({
123
+ DeleteRequest: {
124
+ TableName: this.opts.tableName,
125
+ Key: {
126
+ id: key
127
+ }
128
+ }
129
+ }))
130
+ }
131
+ };
132
+ const response = await this.client.batchWrite(batchDeleteInput);
133
+ return Boolean(response);
134
+ }
135
+ async clear() {
136
+ const scanResult = await this.client.scan({
137
+ TableName: this.opts.tableName
138
+ });
139
+ const keys = this.extractKey(scanResult);
140
+ await this.deleteMany(keys);
141
+ }
142
+ extractKey(output, keyProperty = "id") {
143
+ return (output.Items ?? []).map((item) => item[keyProperty]).filter((key) => key.startsWith(this.namespace ?? ""));
144
+ }
145
+ };
146
+ var index_default = KeyvDynamo;
147
+ // Annotate the CommonJS export names for ESM import in node:
148
+ 0 && (module.exports = {
149
+ KeyvDynamo
150
+ });
@@ -0,0 +1,30 @@
1
+ import EventEmitter from 'events';
2
+ import { DynamoDBClientConfig } from '@aws-sdk/client-dynamodb';
3
+ import { KeyvStoreAdapter, StoredData } from 'keyv';
4
+
5
+ declare class KeyvDynamo extends EventEmitter implements KeyvStoreAdapter {
6
+ ttlSupport: boolean;
7
+ sixHoursInMilliseconds: number;
8
+ namespace?: string;
9
+ opts: Omit<KeyvDynamoOptions, 'tableName'> & {
10
+ tableName: string;
11
+ };
12
+ private readonly client;
13
+ constructor(options: KeyvDynamoOptions | string);
14
+ checkTableExists(tableName: string): Promise<void>;
15
+ set(key: string, value: unknown, ttl?: number): Promise<void>;
16
+ get<Value>(key: string): Promise<StoredData<Value>>;
17
+ delete(key: string): Promise<boolean>;
18
+ getMany<Value>(keys: string[]): Promise<Array<StoredData<Value | undefined>>>;
19
+ deleteMany(keys: string[]): Promise<boolean>;
20
+ clear(): Promise<void>;
21
+ private extractKey;
22
+ }
23
+
24
+ type KeyvDynamoOptions = {
25
+ namespace?: string;
26
+ dialect?: string;
27
+ tableName?: string;
28
+ } & DynamoDBClientConfig;
29
+
30
+ export { KeyvDynamo, type KeyvDynamoOptions, KeyvDynamo as default };
@@ -0,0 +1,30 @@
1
+ import EventEmitter from 'events';
2
+ import { DynamoDBClientConfig } from '@aws-sdk/client-dynamodb';
3
+ import { KeyvStoreAdapter, StoredData } from 'keyv';
4
+
5
+ declare class KeyvDynamo extends EventEmitter implements KeyvStoreAdapter {
6
+ ttlSupport: boolean;
7
+ sixHoursInMilliseconds: number;
8
+ namespace?: string;
9
+ opts: Omit<KeyvDynamoOptions, 'tableName'> & {
10
+ tableName: string;
11
+ };
12
+ private readonly client;
13
+ constructor(options: KeyvDynamoOptions | string);
14
+ checkTableExists(tableName: string): Promise<void>;
15
+ set(key: string, value: unknown, ttl?: number): Promise<void>;
16
+ get<Value>(key: string): Promise<StoredData<Value>>;
17
+ delete(key: string): Promise<boolean>;
18
+ getMany<Value>(keys: string[]): Promise<Array<StoredData<Value | undefined>>>;
19
+ deleteMany(keys: string[]): Promise<boolean>;
20
+ clear(): Promise<void>;
21
+ private extractKey;
22
+ }
23
+
24
+ type KeyvDynamoOptions = {
25
+ namespace?: string;
26
+ dialect?: string;
27
+ tableName?: string;
28
+ } & DynamoDBClientConfig;
29
+
30
+ export { KeyvDynamo, type KeyvDynamoOptions, KeyvDynamo as default };
package/dist/index.js ADDED
@@ -0,0 +1,120 @@
1
+ // src/index.ts
2
+ import EventEmitter from "events";
3
+ import {
4
+ DescribeTableCommand,
5
+ DynamoDB
6
+ } from "@aws-sdk/client-dynamodb";
7
+ import {
8
+ DynamoDBDocument
9
+ } from "@aws-sdk/lib-dynamodb";
10
+ var KeyvDynamo = class extends EventEmitter {
11
+ ttlSupport = true;
12
+ sixHoursInMilliseconds = 6 * 60 * 60 * 1e3;
13
+ namespace;
14
+ opts;
15
+ client;
16
+ constructor(options) {
17
+ super();
18
+ options ??= {};
19
+ if (typeof options === "string") {
20
+ options = { endpoint: options };
21
+ }
22
+ this.opts = {
23
+ tableName: "keyv",
24
+ dialect: "dynamo",
25
+ ...options
26
+ };
27
+ this.client = DynamoDBDocument.from(new DynamoDB(this.opts));
28
+ this.checkTableExists(this.opts.tableName).catch((error) => {
29
+ this.emit("error", error);
30
+ });
31
+ }
32
+ async checkTableExists(tableName) {
33
+ await this.client.send(new DescribeTableCommand({ TableName: tableName }));
34
+ }
35
+ async set(key, value, ttl) {
36
+ const sixHoursFromNowEpoch = Math.floor((Date.now() + this.sixHoursInMilliseconds) / 1e3);
37
+ const expiresAt = typeof ttl === "number" ? Math.floor((Date.now() + (ttl + 1e3)) / 1e3) : sixHoursFromNowEpoch;
38
+ const putInput = {
39
+ TableName: this.opts.tableName,
40
+ Item: {
41
+ id: key,
42
+ value,
43
+ expiresAt
44
+ }
45
+ };
46
+ await this.client.put(putInput);
47
+ }
48
+ async get(key) {
49
+ const getInput = {
50
+ TableName: this.opts.tableName,
51
+ Key: {
52
+ id: key
53
+ }
54
+ };
55
+ const { Item } = await this.client.get(getInput);
56
+ return Item?.value;
57
+ }
58
+ async delete(key) {
59
+ const deleteInput = {
60
+ TableName: this.opts.tableName,
61
+ Key: {
62
+ id: key
63
+ },
64
+ ReturnValues: "ALL_OLD"
65
+ };
66
+ const { Attributes } = await this.client.delete(deleteInput);
67
+ return Boolean(Attributes);
68
+ }
69
+ async getMany(keys) {
70
+ const batchGetInput = {
71
+ RequestItems: {
72
+ [this.opts.tableName]: {
73
+ Keys: keys.map((key) => ({
74
+ id: key
75
+ }))
76
+ }
77
+ }
78
+ };
79
+ const { Responses: { [this.opts.tableName]: items = [] } = {} } = await this.client.batchGet(batchGetInput);
80
+ return keys.map((key) => items.find((item) => item?.id === key)?.value);
81
+ }
82
+ async deleteMany(keys) {
83
+ if (keys.length === 0) {
84
+ return false;
85
+ }
86
+ const items = await this.getMany(keys);
87
+ if (items.filter(Boolean).length === 0) {
88
+ return false;
89
+ }
90
+ const batchDeleteInput = {
91
+ RequestItems: {
92
+ [this.opts.tableName]: keys.map((key) => ({
93
+ DeleteRequest: {
94
+ TableName: this.opts.tableName,
95
+ Key: {
96
+ id: key
97
+ }
98
+ }
99
+ }))
100
+ }
101
+ };
102
+ const response = await this.client.batchWrite(batchDeleteInput);
103
+ return Boolean(response);
104
+ }
105
+ async clear() {
106
+ const scanResult = await this.client.scan({
107
+ TableName: this.opts.tableName
108
+ });
109
+ const keys = this.extractKey(scanResult);
110
+ await this.deleteMany(keys);
111
+ }
112
+ extractKey(output, keyProperty = "id") {
113
+ return (output.Items ?? []).map((item) => item[keyProperty]).filter((key) => key.startsWith(this.namespace ?? ""));
114
+ }
115
+ };
116
+ var index_default = KeyvDynamo;
117
+ export {
118
+ KeyvDynamo,
119
+ index_default as default
120
+ };
package/package.json ADDED
@@ -0,0 +1,82 @@
1
+ {
2
+ "name": "@keyv/dynamo",
3
+ "version": "1.0.0",
4
+ "description": "DynamoDB storage adapter for Keyv",
5
+ "type": "module",
6
+ "main": "dist/index.cjs",
7
+ "module": "dist/index.js",
8
+ "types": "dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "require": "./dist/index.cjs",
12
+ "import": "./dist/index.js"
13
+ }
14
+ },
15
+ "xo": {
16
+ "space": true,
17
+ "rules": {
18
+ "import/no-named-as-default": "off",
19
+ "unicorn/prefer-module": "off",
20
+ "unicorn/prefer-event-target": "off",
21
+ "unicorn/no-array-reduce": "off",
22
+ "unicorn/prefer-object-from-entries": "off",
23
+ "unicorn/prefer-node-protocol": "off",
24
+ "@typescript-eslint/no-unsafe-assignment": "off",
25
+ "@typescript-eslint/no-unsafe-call": "off",
26
+ "@typescript-eslint/no-unsafe-return": "off",
27
+ "@typescript-eslint/no-unsafe-argument": "off",
28
+ "import/extensions": "off",
29
+ "@typescript-eslint/consistent-type-imports": "off",
30
+ "@typescript-eslint/naming-convention": "off",
31
+ "@typescript-eslint/no-floating-promises": "off",
32
+ "import/no-extraneous-dependencies": "off",
33
+ "@typescript-eslint/no-confusing-void-expression": "off",
34
+ "@typescript-eslint/no-empty-function": "off",
35
+ "promise/prefer-await-to-then": "off"
36
+ }
37
+ },
38
+ "repository": {
39
+ "type": "git",
40
+ "url": "git+https://github.com/jaredwray/keyv.git"
41
+ },
42
+ "keywords": [
43
+ "dynamo",
44
+ "dynamodb",
45
+ "keyv",
46
+ "storage",
47
+ "adapter",
48
+ "key",
49
+ "value",
50
+ "store",
51
+ "cache",
52
+ "ttl"
53
+ ],
54
+ "author": "Jared Wray <me@jaredwray.com> (https://jaredwray.com)",
55
+ "license": "MIT",
56
+ "bugs": {
57
+ "url": "https://github.com/jaredwray/keyv/issues"
58
+ },
59
+ "homepage": "https://github.com/jaredwray/keyv",
60
+ "dependencies": {
61
+ "@aws-sdk/client-dynamodb": "^3.835.0",
62
+ "@aws-sdk/lib-dynamodb": "^3.835.0"
63
+ },
64
+ "devDependencies": {
65
+ "vitest": "^3.2.4",
66
+ "keyv": "^5.3.4",
67
+ "@keyv/test-suite": "^2.0.9"
68
+ },
69
+ "tsd": {
70
+ "directory": "test"
71
+ },
72
+ "files": [
73
+ "dist",
74
+ "LICENSE"
75
+ ],
76
+ "scripts": {
77
+ "build": "rimraf ./dist && tsup src/index.ts --format cjs,esm --dts --clean",
78
+ "test": "xo --fix && vitest run --coverage",
79
+ "test:ci": "xo && vitest --run --sequence.setupFiles=list --coverage",
80
+ "clean": "rimraf ./node_modules ./coverage ./dist"
81
+ }
82
+ }