forked from aaronshaf/dynamodb-admin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
516 lines (471 loc) · 13.4 KB
/
index.js
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
const express = require('express')
const _ = require('lodash')
const AWS = require('aws-sdk')
const promisify = require('es6-promisify')
const path = require('path')
const errorhandler = require('errorhandler')
const { extractKey, parseKey } = require('./util')
const bodyParser = require('body-parser')
const pickBy = require('lodash/pickBy')
const omit = require('lodash/omit')
const yaml = require('js-yaml')
const querystring = require('querystring')
const clc = require('cli-color')
require('es7-object-polyfill')
console.log('dynamodb-admin')
if (process.env.NODE_ENV === 'production') {
console.error(clc.red('Do not run this in production!'))
process.exit(1)
}
const app = express()
app.set('json spaces', 2)
app.set('view engine', 'ejs')
app.set('views', path.resolve(__dirname, 'views'))
const env = process.env
const awsConfig = {
region: env.AWS_REGION || 'us-east-1',
accessKeyId: env.AWS_ACCESS_KEY_ID || 'key', // DynamoDB Local doesn't care what the key/secret are
secretAccessKey: env.AWS_SECRET_ACCESS_KEY || 'secret'
}
if (typeof env.DYNAMO_ENDPOINT === 'string') {
if (env.DYNAMO_ENDPOINT.indexOf('.amazonaws.com') > -1) {
console.error(
clc.red('dynamodb-admin is only intended for local development')
)
process.exit(1)
}
awsConfig.endpoint = env.DYNAMO_ENDPOINT.replace(/\"/g, '');
awsConfig.sslEnabled = env.DYNAMO_ENDPOINT.indexOf('https://') === 0
} else {
awsConfig.endpoint = 'http://localhost:8000'
awsConfig.sslEnabled = false
console.log(
clc.yellow(
` DYNAMO_ENDPOINT is not defined (using default of http://localhost:8000)`
)
)
}
AWS.config.update(awsConfig)
const dynamodb = new AWS.DynamoDB()
const docClient = new AWS.DynamoDB.DocumentClient()
const listTables = promisify(dynamodb.listTables.bind(dynamodb))
const describeTable = promisify(dynamodb.describeTable.bind(dynamodb))
const getItem = promisify(docClient.get.bind(docClient))
const putItem = promisify(docClient.put.bind(docClient))
const deleteItem = promisify(docClient.delete.bind(docClient))
app.use(errorhandler())
app.use('/assets', express.static(path.join(__dirname, '/public')))
app.get('/', (req, res) => {
dynamodb.listTables({}, (error, data) => {
if (error) {
res.json({ error })
} else {
Promise.all(
data.TableNames.map(TableName => {
return describeTable({ TableName }).then(data => data.Table)
})
)
.then(data => {
res.render('tables', { data })
})
.catch(error => {
res.json({ error })
})
}
})
})
app.get('/create-table', (req, res) => {
res.render('create-table', {})
})
app.post(
'/create-table',
bodyParser.urlencoded({ extended: false }),
(req, res, next) => {
let attributeDefinitions = [
{
AttributeName: req.body.HashAttributeName,
AttributeType: req.body.HashAttributeType
}
]
let keySchema = [
{
AttributeName: req.body.HashAttributeName,
KeyType: 'HASH'
}
]
if (req.body.RangeAttributeName) {
attributeDefinitions.push({
AttributeName: req.body.RangeAttributeName,
AttributeType: req.body.RangeAttributeType
})
keySchema.push({
AttributeName: req.body.RangeAttributeName,
KeyType: 'RANGE'
})
}
dynamodb
.createTable({
TableName: req.body.TableName,
ProvisionedThroughput: {
ReadCapacityUnits: req.body.ReadCapacityUnits,
WriteCapacityUnits: req.body.WriteCapacityUnits
},
KeySchema: keySchema,
AttributeDefinitions: attributeDefinitions
})
.promise()
.then(response => {
res.redirect('/')
})
.catch(next)
}
)
app.delete('/tables/:TableName', (req, res, next) => {
const TableName = req.params.TableName
dynamodb
.deleteTable({ TableName })
.promise()
.then(() => {
res.status(204).end()
})
.catch(next)
})
app.get('/tables/:TableName/get', (req, res, next) => {
const TableName = req.params.TableName
if (req.query.hash) {
if (req.query.range) {
return res.redirect(
`/tables/${TableName}/items/${req.query.hash}${encodeURIComponent(
','
)}${req.query.range}`
)
} else {
return res.redirect(`/tables/${TableName}/items/${req.query.hash}`)
}
}
describeTable({ TableName }).then(description => {
const hashKey = description.Table.KeySchema.find(schema => {
return schema.KeyType === 'HASH'
})
if (hashKey) {
hashKey.AttributeType = description.Table.AttributeDefinitions.find(
definition => {
return definition.AttributeName === hashKey.AttributeName
}
).AttributeType
}
const rangeKey = description.Table.KeySchema.find(schema => {
return schema.KeyType === 'RANGE'
})
if (rangeKey) {
rangeKey.AttributeType = description.Table.AttributeDefinitions.find(
definition => {
return definition.AttributeName === rangeKey.AttributeName
}
).AttributeType
}
res.render(
'get',
Object.assign({}, description, {
hashKey,
rangeKey
})
)
})
})
var doSearch = function(
docClient,
tableName,
scanParams,
limit,
startKey,
done,
progress,
readOperation = 'scan'
) {
limit = typeof limit !== 'undefined' ? limit : null
startKey = typeof startKey !== 'undefined' ? startKey : null
var self = this
var params = { TableName: tableName }
if (typeof scanParams !== 'undefined' && scanParams) {
params = _.assign(params, scanParams)
}
if (limit != null) params.Limit = limit
if (startKey != null) params.ExclusiveStartKey = startKey
var items = []
var processNextBite = function(err, items, nextKey) {
if (!err && nextKey) {
params.ExclusiveStartKey = nextKey
getNextBite(params, items, processNextBite)
} else {
if (done) done(err, items)
}
}
var readMethod = {
scan: docClient.scan,
query: docClient.query
}[readOperation].bind(docClient)
var getNextBite = function(params, items, callback) {
var result = readMethod(params, function(err, data) {
var obj = null
if (err != null) {
obj = null
callback(err, items, null)
return
}
if (typeof data.Items == 'undefined') {
}
if (data && data.Items && data.Items.length > 0)
items = items.concat(data.Items)
var lastStartKey = null
if (data) lastStartKey = data.LastEvaluatedKey
if (progress) {
var stop = progress(err, data.Items, lastStartKey)
if (!stop) {
callback(err, items, lastStartKey)
} else {
if (done) done(err, items)
}
} else {
callback(err, items, lastStartKey)
}
})
}
getNextBite(params, items, processNextBite)
}
var getPage = function(
docClient,
keySchema,
TableName,
scanParams,
pageSize,
startKey,
done
) {
var pageItems = []
doSearch(
docClient,
TableName,
scanParams,
10,
startKey,
function(err, items) {
let nextKey = null
if (_.size(pageItems) > pageSize) {
pageItems = pageItems.slice(0, pageSize)
nextKey = extractKey(pageItems[pageSize - 1], keySchema)
}
done(pageItems, err, nextKey)
},
function(err, items, lastStartKey) {
for (
let i = 0;
i < items.length && _.size(pageItems) < pageSize + 1;
i++
) {
let item = items[i]
pageItems.push(item)
}
if (_.size(pageItems) >= pageSize || !lastStartKey) {
return true
} else return false
}
)
}
app.get('/tables/:TableName', (req, res, next) => {
const TableName = req.params.TableName
req.query = pickBy(req.query)
const filters = omit(req.query, ['_hash', 'range', 'startKey', 'pageNum'])
describeTable({ TableName })
.then(description => {
let ExclusiveStartKey = req.query.startKey
? JSON.parse(req.query.startKey)
: {}
let pageNum = req.query.pageNum ? parseInt(req.query.pageNum) : 1
const ExpressionAttributeNames = {}
const ExpressionAttributeValues = {}
const KeyConditionExpression = []
const FilterExpressions = []
for (let key in filters) {
const attributeDefinition = description.Table.AttributeDefinitions.find(
definition => {
return definition.AttributeName === key
}
)
if (attributeDefinition && attributeDefinition.AttributeType === 'N') {
req.query[key] = Number(req.query[key])
}
ExpressionAttributeNames[`#${key}`] = key
ExpressionAttributeValues[`:${key}`] = req.query[key]
const isSchemaKey = description.Table.KeySchema.find(definition => {
return definition.AttributeName === key
})
FilterExpressions.push(`#${key} = :${key}`)
}
const params = pickBy({
TableName,
FilterExpression: FilterExpressions.length
? FilterExpressions.join(' AND ')
: undefined,
ExpressionAttributeNames: Object.keys(ExpressionAttributeNames).length
? ExpressionAttributeNames
: undefined,
ExpressionAttributeValues: Object.keys(ExpressionAttributeValues).length
? ExpressionAttributeValues
: undefined
})
let startKey = Object.keys(ExclusiveStartKey).length
? ExclusiveStartKey
: undefined
getPage(
docClient,
description.Table.KeySchema,
TableName,
params,
25,
startKey,
function(pageItems, err, nextKey) {
let nextKeyParam = nextKey
? encodeURIComponent(JSON.stringify(nextKey))
: null
const data = Object.assign({}, description, {
query: req.query,
yaml,
omit,
filters,
pageNum: pageNum,
nextKey: nextKeyParam,
filterQueryString: querystring.stringify(filters),
Items: pageItems.map(item => {
return Object.assign({}, item, {
__key: extractKey(item, description.Table.KeySchema)
})
})
})
res.render('scan', data)
}
)
})
.catch(next)
})
app.get('/tables/:TableName/meta', (req, res) => {
const TableName = req.params.TableName
Promise.all([
describeTable({ TableName }),
docClient.scan({ TableName }).promise()
])
.then(([description, items]) => {
const data = Object.assign({}, description, items)
res.render('meta', data)
})
.catch(error => {
res.json({ error })
})
})
app.delete('/tables/:TableName/items/:key', (req, res, next) => {
const TableName = req.params.TableName
describeTable({ TableName })
.then(result => {
const params = {
TableName,
Key: parseKey(req.params.key, result.Table)
}
return deleteItem(params).then(response => {
res.status(204).end()
})
})
.catch(next)
})
app.get('/tables/:TableName/add-item', (req, res, next) => {
const TableName = req.params.TableName
describeTable({ TableName })
.then(result => {
const table = result.Table
const Item = {}
table.KeySchema.forEach(key => {
const definition = table.AttributeDefinitions.find(attribute => {
return attribute.AttributeName === key.AttributeName
})
Item[key.AttributeName] = definition.AttributeType === 'S' ? '' : 0
})
res.render('item', {
TableName: req.params.TableName,
Item: Item,
isNew: true
})
})
.catch(next)
})
app.get('/tables/:TableName/items/:key', (req, res, next) => {
const TableName = req.params.TableName
describeTable({ TableName })
.then(result => {
const params = {
TableName,
Key: parseKey(req.params.key, result.Table)
}
return getItem(params).then(response => {
if (!response.Item) {
return res.status(404).send('Not found')
}
res.render('item', {
TableName: req.params.TableName,
Item: response.Item,
isNew: false
})
})
})
.catch(next)
})
app.put('/tables/:TableName/add-item', bodyParser.json(), (req, res, next) => {
const TableName = req.params.TableName
describeTable({ TableName })
.then(description => {
const params = {
TableName,
Item: req.body
}
return putItem(params).then(response => {
const Key = extractKey(req.body, description.Table.KeySchema)
const params = {
TableName,
Key
}
return getItem(params).then(response => {
if (!response.Item) {
return res.status(404).send('Not found')
}
return res.json(Key)
})
})
})
.catch(next)
})
app.put(
'/tables/:TableName/items/:key',
bodyParser.json(),
(req, res, next) => {
const TableName = req.params.TableName
describeTable({ TableName })
.then(result => {
const params = {
TableName,
Item: req.body
}
return putItem(params).then(() => {
const params = {
TableName,
Key: parseKey(req.params.key, result.Table)
}
return getItem(params).then(response => {
return res.json(response.Item)
})
})
})
.catch(next)
}
)
const port = process.env.PORT || 8001
app.listen(port, () => {
console.log(` listening on port ${port}`)
})