-
Notifications
You must be signed in to change notification settings - Fork 0
/
dynamo.js
82 lines (76 loc) · 2.19 KB
/
dynamo.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
const dynamo = require('dynamodb');
const Joi = require('joi');
const Constants = require('./constants');
const moment = require('moment');
async function getTransaction(id) {
return new Promise((res, rej) => {
return Player.get(id, {ConsistentRead: true}, (err, player) => {
if (err) {
console.log('Error getting transaction ' + id);
return rej(err)
} else {
console.log('got transaction ' + id);
return res(player);
}
})
})
}
async function putTransaction(amount, category, card, description) {
let id = `${moment().utc().format('YYYY-MM-DD')}-${card}-${amount}`
let date = moment().utc().unix();
let params = {
id, date, amount, category, description
}
return new Promise((res, rej) => {
return Transaction.create(params, (err, transaction) => {
if (err) return rej(err)
return res(transaction);
})
})
}
async function updateTransaction(params) {
return new Promise((res, rej) => {
return Transaction.update(params, (err, transaction) => {
if (err) return rej(err)
return res(transaction);
})
})
}
async function getRange(range) {
let start, end;
if (range === Constants.MONTH) {
start = moment().startOf('month').unix();
end = moment().endOf('month').unix();
} else {
start = moment().startOf('week').unix();
end = moment().endOf('week').unix();
}
return new Promise((res, rej) => {
return Transaction
.scan()
.where('date').between(start,end)
.loadAll()
.exec( (err, data) => {
if (err) rej(err)
res(data)
})
})
}
const Transaction = dynamo.define('Transaction', {
hashKey: 'id',
timestamps: true,
schema: Joi.object({
id: Joi.string(),
amount: Joi.number(),
category: Joi.string(),
date: Joi.number(),
description: Joi.string()
}),
tableName: process.env.TRANSACTION_DB
})
module.exports = {
putTransaction,
getTransaction,
getRange,
updateTransaction
}