Created
December 17, 2016 12:10
-
-
Save samcorcos/1c251bb635cf860f2c5676fbb7c37ccc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MockDynamoDB { | |
constructor() { | |
this.tables = {} | |
} | |
get(params, callback) { | |
/** if table does not exist, return with an error */ | |
if (!this.tables[params.TableName]) callback({ message: 'no items in table', }, null) | |
else { | |
const key = Object.keys(params.Key)[0] // e.g. user_id | |
const hash = params.Key[key] // e.g. user|123 | |
const Item = this.tables[params.TableName].filter((item) => { | |
return item[key] === hash | |
})[0] // e.g. { user_id, org_ids, ... } | |
callback(null, { | |
Item, | |
}) | |
} | |
} | |
put(params, callback) { | |
/** if table does not exist, create it */ | |
if (!this.tables[params.TableName]) this.tables[params.TableName] = [] | |
/** then add the data to the table */ | |
this.tables[params.TableName].push(params.Item) | |
/** then return empty object because DynamoDB does not return an id */ | |
callback(null, {}) | |
} | |
query(params, callback) { | |
if (!this.tables[params.TableName]) callback({ message: 'no items in table', }, null) | |
else { | |
// eslint-disable-next-line | |
const Items = this.tables[params.TableName].filter((item) => { | |
const cond = params.KeyConditionExpression | |
const values = params.ExpressionAttributeValues | |
const names = params.ExpressionAttributeNames | |
const a = cond.replace(/( and )/g, ' && ') | |
const b = a.replace(/( = )/g, ' === ') | |
const c = b.replace(/( or )/g, ' || ') | |
const d = cond.match(/(:\w+)/g).reduce((acc, key) => { | |
const re = new RegExp(key, 'g') | |
return acc.replace(re, `'${values[key]}'`) | |
}, c) | |
const e = cond.match(/(#\w+)/g).reduce((acc, key) => { | |
const re = new RegExp(key, 'g') | |
return acc.replace(re, `item.${names[key]}`) | |
}, d) | |
// eslint-disable-next-line | |
return eval(e) | |
}) | |
callback(null, { | |
Items, | |
}) | |
} | |
} | |
} | |
export default MockDynamoDB |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment