From 3bc27376f0277741fa946f09e35c5e682b79812d Mon Sep 17 00:00:00 2001 From: iaforek Date: Wed, 4 Oct 2017 12:23:35 +0100 Subject: [PATCH] Refactored the code. Works with mocks now. Changed object properties to methods in order to get this to work with mocks. When running `sls invoke test` isOffline() will return false. Therefore, you must set IS_OFFFLINE=true as environment variable manually prior running test locally or you can add to your tests: before((done) => { process.env.IS_OFFLINE = true; ... done(); }); and after((done) => { delete process.env.IS_OFFLINE; ... done(); }); In the code use: `docClient = dynamodb.doc()` instead of `const docClient = dynamodb.doc`. This will work with AWS, serverless offline and mocks. Additionally, made ESLint changes. --- index.js | 27 +++++++++++++++++---------- 1 file changed, 17 insertions(+), 10 deletions(-) diff --git a/index.js b/index.js index e0dd69d..3ebaeb1 100644 --- a/index.js +++ b/index.js @@ -1,16 +1,23 @@ -var AWS = require('aws-sdk'), - options = { - region: "localhost", - endpoint: "http://localhost:8000" - }; +const AWS = require('aws-sdk'); -var isOffline = function () { +const options = { + region: 'localhost', + endpoint: 'http://localhost:8000' +}; + +/** + * Check IS_OFFLINE environment variable is set. + * + * @returns {boolean} + */ +function isOffline() { // Depends on serverless-offline plugion which adds IS_OFFLINE to process.env when running offline return process.env.IS_OFFLINE; -}; +} -var dynamodb = { - doc: isOffline() ? new AWS.DynamoDB.DocumentClient(options) : new AWS.DynamoDB.DocumentClient(), - raw: isOffline() ? new AWS.DynamoDB(options) : new AWS.DynamoDB() +const dynamodb = { + doc() { return isOffline() ? new AWS.DynamoDB.DocumentClient(options) : new AWS.DynamoDB.DocumentClient(); }, + raw() { return isOffline() ? new AWS.DynamoDB(options) : new AWS.DynamoDB(); } }; + module.exports = dynamodb;