-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdeps.ts
More file actions
98 lines (91 loc) · 2.65 KB
/
deps.ts
File metadata and controls
98 lines (91 loc) · 2.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import { createClient as create } from "https://denopkg.com/chiefbiiko/dynamodb/mod.ts";
import { Hashids } from "https://raw.githubusercontent.com/smallwins/deno-hashids/master/mod.js";
/** get a ddb client */
export function createClient() {
let env = Deno.env.toObject();
// running locally
if (env.NODE_ENV === "testing" || env.DENO_ENV === "testing") {
let conf = {
credentials: {
accessKeyId: "DynamoDBLocal",
secretAccessKey: "DoesNotDoAnyAuth",
sessionToken: "preferTemporaryCredentials",
},
region: "local",
port: 5000,
};
return create(conf);
}
// running in staging or production
return create({
credentials: {
accessKeyId: env.AWS_ACCESS_KEY_ID,
secretAccessKey: env.AWS_SECRET_ACCESS_KEY,
sessionToken: env.AWS_SESSION_TOKEN,
},
});
}
/** get the begin/data dynamodb table name */
export async function getTableName() {
let env = Deno.env.toObject();
// allow override
if (env.BEGIN_DATA_TABLE_NAME) {
return env.BEGIN_DATA_TABLE_NAME;
}
// check for local sandbox testing
if (env.NODE_ENV === "testing" || env.DENO_ENV === "testing") {
let db = createClient();
let result = await db.listTables();
return result.TableNames.find((t: string) => t.includes("-staging-data"));
} else {
// TODO SSM lookup here
}
}
/** get a begin/data key schema given options */
export function getKey(opts: { table: string; key?: string }) {
let env = Deno.env.toObject();
let stage = env.DENO_ENV === "testing"
? "staging"
: (env.DENO_ENV || "staging");
let scopeID = env.BEGIN_DATA_SCOPE_ID || env.ARC_APP_NAME || "sandbox";
let dataID = `${stage}#${opts.table}#${opts.key}`;
return {
scopeID,
dataID,
};
}
/** create a key */
export async function createKey(table: string) {
let TableName = await getTableName();
let db = createClient();
let env = Deno.env.toObject();
let scopeID = env.BEGIN_DATA_SCOPE_ID || env.ARC_APP_NAME || "sandbox";
let dataID = `${table}-seq`;
let result = await db.updateItem({
TableName,
Key: { scopeID, dataID },
AttributeUpdates: {
idx: {
Action: "ADD",
Value: 1,
},
},
ReturnValues: "UPDATED_NEW",
});
let hash = new Hashids();
let epoc = Date.now() - 1544909702376; // hbd
let seed = Number(result.Attributes.idx);
return hash.encode([epoc, seed]);
}
/** convert an object from ddb */
export function unfmt(obj: { [others: string]: any }) {
if (!obj) {
return null;
}
let copy = { ...obj };
copy.key = obj.dataID.split("#")[2];
copy.table = obj.dataID.split("#")[1];
delete copy.scopeID;
delete copy.dataID;
return copy;
}