I am working on lex and I am trying to store user data in DynamoDB while using NodeJS
Here is my code:
'use strict';
const uuidV1 = require('uuid/v1');
const AWS = require('aws-sdk');
const promisify = require('es6-promisify');
const dynamo = new AWS.DynamoDB.DocumentClient();
module.exports.saveBookingToDatabase = function(Arrival_city, Departure_city, Flight_type, Phone_number){
console.log('saveBookingToDatabase');
const item = {};
item.bookingId = uuidV1();
item.arrivalCity = Arrival_city;
item.departureCity = Departure_city;
item.classType = Flight_type;
item.phone = Phone_number;
const params = {
TableName: 'airstallion',
Item: item
};
const putAsync = promisify(dynamo.put, dynamo);
return putAsync(params).then(() => {
console.log(`Saving ticket ${JSON.stringify(item)}`);
return item;
})
.catch(error => {
Promise.reject(error);
});
}
When i run the program is returning the following error
Since aws-sdk library supports promise, its not necessary to use es6-promisify library. Using node.js async/await we shall achieve the same use case.
'use strict';
const uuidV1 = require('uuid/v1');
const AWS = require('aws-sdk');
const dynamo = new AWS.DynamoDB.DocumentClient();
module.exports.saveBookingToDatabase = async function(Arrival_city, Departure_city, Flight_type, Phone_number){
console.log('saveBookingToDatabase');
const item = {};
item.bookingId = uuidV1();
item.arrivalCity = Arrival_city;
item.departureCity = Departure_city;
item.classType = Flight_type;
item.phone = Phone_number;
const params = {
TableName: 'airstallion',
Item: item
};
try {
let result = await dynamo.put(params)
console.log(`Saving ticket ${JSON.stringify(item)}`);
return item;
} catch(e) {
throw (e)
}
}
Related
I guess I am missing something quite obvious. Why cannot I query the db and I am getting this error:
TypeError: client.query is not a function
The code is quite simple:
const consts = require('./constants');
const bcrypt = require('bcrypt');
const process = require('process');
require('dotenv').config();
const { Client } = require("pg")
const command = "login_user"
const pass = "login_user"
const client = connectToDb();
if (command === consts.LOGIN_USER) {
loginUser(client, pass);
}
async function connectToDb() {
const dbClient = new Client({});
await dbClient.connect();
return dbClient;
}
async function loginUser(client, pass) {
const query = { text: 'SELECT * FROM users' }
const res = await client.query(query).rows;
console.log(res);
await client.end();
}
The credentials for the db are in the .env file.
I suppose the problem was that the connectToDb() function needs to be called from within an async function.
Here's the code which I got working:
handleInput();
async function handleInput() {
const client = await connectToDb();
if (command === consts.LOGIN_USER) {
await loginUser(client, username, pass);
}
await client.end();
}
async function connectToDb() {
const dbClient = new Client({});
await dbClient.connect();
return dbClient;
}
async function loginUser(client, username, pass) {
// Some operations with db
}
I'm totally new to Jest and typescript. my 2nd test case to be honest.
I want in my jest test - when s3.getObject is called in the actual class, it should return the mocked value.
my handler code:
var aws = require("aws-sdk");
var s3 = new aws.S3({apiVersion: '2006-03-01'});
exports.handler = async function (event, context, callback) {
const bucket = 'event.s3.bucket.name';
const filename = 'fileName';
const inputBucketParams = {
Bucket: bucket,
Key: filename,
};
let result;
try {
**//I want the result to be the mocked value in my test case.**
result = await s3.getObject(inputBucketParams).promise();
const fileContent = getFileContents(result.Body.toString("utf-8"));
my test case:
import {getFileContent} from "../../utils/FileContent";
import anything = jasmine.anything;
const lambdaHandler = require('../lambda/myLambda');
const AWSMock = require('aws-sdk-mock');
const AWS = require("aws-sdk");
describe('Test getS3Object', () => {
beforeEach(() => AWSMock.setSDKInstance(AWS));
})
let s3Object = {
"bucket": {
},
"object": {
}
};
let event = {Records: [
{
s3: s3Object --> from above.
}
]
}
var aws = require("aws-sdk");
var s3 = new aws.S3({apiVersion: '2006-03-01'});
describe('my handler test', async function () {
const s3GetObject = AWSMock.mock('S3', 'getObject', getFileContent('fileName.csv'));
const s3mock = jest.fn();
const getObjectMock = jest.fn(() => getFileContent('fileName.csv'));
const params = {
Bucket: 'bucketName',
Key: 'filename'
}
var returnValue = s3mock.mockReturnValue({
Body: getFileContent('fileName.csv')
});
test('s3 getObject response mock', async () => {
//jest.spyOn(s3, "getObject")
const getObjectMockValue = s3.spyOn('S3', 'getObject').mockReturnValue({
Body: getFileContent('fileName.csv')
})
// my handler is called from this, and when it get to s3.getObject, it fails.
const handlerResponse = await lambdaHandler.handler(event, anything(), anything());
});
});
I want in my jest test - when s3.getObject is called in the actual class, it should return the mocked value.
I'm trying to interact with a BSC Smartcontract using Ethersjs and here is my code:
require("dotenv").config();
const { ethers } = require("ethers");
const pk = process.env.PRIVATE_KEY;
const bsc_jsonRPC_testnet = "https://data-seed-prebsc-1-s1.binance.org:8545/" // json RPC url
const provider = new ethers.providers.JsonRpcProvider(bsc_jsonRPC_testnet);
let wallet = new ethers.Wallet(pk, provider);
const CONTRACT_ABI = require('./abis/vino.json'); // set ABI
const CONTRACT_ADDRESS = '0x21f59c8D31EF2E3E472793b28CAc4553aac7a72a';
let contract = new ethers.Contract(CONTRACT_ADDRESS, CONTRACT_ABI, provider);
var numberOfDecimals = 18;
const activeProvider = contract.provider.connection.url;
const methods = contract.functions
console.log(methods.name().then((res) => {
console.log(res)
}).catch((e) => {
console.log(e)
}));
console.log('URL PROVIDER: ', activeProvider);
And here what I'm getting from console:
I tried changing chains and providers but no success.
I cannot able to validate the webhook response from the shopify by using the "crypto-js" package.
i am using: "Node.js, AWS-Lambda , crypto-js" and the following code to validate
var CryptoJS = require("crypto-js");
var getRawBody = require("raw-body");
var Buffer = require('buffer/').Buffer // note: the trailing slash is important!
exports.handler = async (event, context) => {
let hmac = event.hmac;
const bodyString = Buffer.from(event.body, "utf8").toString();
var bodyForVerification = bodyString.replace('/\\/g', '\\\\');
let firma = CryptoJS.HmacSHA256(bodyForVerification, "****");
var hashInBase64 = CryptoJS.enc.Base64.stringify(firma);
let calculatedHmacBase = hashInBase64.toString(CryptoJS.enc.hex);
if(hmac == calculatedHmacBase {
console.log("verificado");
}
};
The HMAC is different..
I use this middleware for my public and private apps on Shopify,
using crypto, it is deprecated but works fine for my code.
const crypto = require('crypto');
const verify = function (req, res, next) {
if (req.query.shop) {
if (!req.query.signature) {
return false;
}
console.log(req.query);
const signature = req.query.signature;
const sharedSecret = process.env.SHOPIFY_SHARED_SECRET;
const def = req.query;
delete def.signature;
const sortedQuery = Object.keys(def).map(key => `${key}=${Array(def[key]).join(',')}`).sort().join('');;
const calculatedSignature = crypto.createHmac('sha256', sharedSecret).update(sortedQuery).digest('hex');
if (calculatedSignature === signature) {
console.log('validated');
return next();
}
console.log('not validated');
return false;
}
};
module.exports = verify;
I have a project with Node JS in which I am collecting the information of a JSON by http using the node-fetch module.
This is the way I have found to use the node-fetch module with async, if it is possible to improve this function, suggestions are added, I am new to this module.
This is my code where I read the information:
const fetch = require('node-fetch');
(async () => {
try {
const res = await fetch('https://jsonplaceholder.typicode.com/users');
const headerDate = res.headers && res.headers.get('date') ? res.headers.get('date') : 'no response date';
const users = await res.json();
for(user of users) {
console.log(`Got user with id: ${user.id}, name: ${user.name}`);
}
} catch (err) {
console.log(err.message); //can be console.error
}
})();
My problem: how can I extract all the information to a CSV with a limit of lines ?, that is, the CSV has a limit of 10 lines (the limit can vary), if the JSON information occupies 30 lines, 3 CSVs would be created to store all the information. I have added the json-2-csv module, but I don't know how to use it or if this module is necessary or something else is better.
const { Parser } = require("json2csv");
const fetch = require("node-fetch");
const fs = require("fs");
const csvLimit = 3;
const getJson = async () => {
const response = await fetch("https://jsonplaceholder.typicode.com/users");
const responseJson = await response.json();
return responseJson;
};
const jsonToCsv = async () => {
const json = await getJson();
const json2csvParser = new Parser();
let i = 0,
j = 0;
while (j < json.length) {
let csv = [];
let temp = [];
for (j = i * csvLimit; j < (i + 1) * csvLimit; j++) {
temp.push(json[j]);
}
csv.push(json2csvParser.parse(temp));
fs.writeFileSync(`file${(i * csvLimit) / 3}.csv`, csv);
i++;
}
};
jsonToCsv();
If you want only specific fields in the csv file, then you can pass the fields as parameter in this way.
const json2csvParser = new Parser({fields})
I used the flat package to extract the field names from the keys of the first record of the JSON and then used the json-2-csv package to convert from JSON to CSV.
const converter = require("json-2-csv");
const fetch = require("node-fetch");
const fs = require("fs");
const flatten = require('flat');
const maxRecords = 3;
const getJson = async () => {
const response = await fetch("https://jsonplaceholder.typicode.com/users");
const responseJson = await response.json();
return responseJson;
};
const convertToCSV = async () => {
const json = await getJson();
let keys = Object.keys(flatten(json[0]));
let options = {
keys: keys
};
converter.json2csv(json, json2csvCallback, options);
};
let json2csvCallback = function (err, csv) {
if (err) throw err;
const headers = csv.split('\n').slice(0,1);
const records = csv.split('\n').slice(0,);
for(let i=1;i<records.length;i=i+maxRecords) {
let dataOut = headers.concat(records.slice(i, i+3)).join('\n');
let id = Math.floor(i/maxRecords)+1;
fs.writeFileSync('data' + id + '.csv', dataOut)
}
};
convertToCSV();
Here's one of the files opened in Excel.