S3, Dynamodb ORM and moment js with timezone npm packages
javascript
let Storage = require('nealyip-aws-lambda-helper/storage');
class S3Example extends Storage {
constructor(){
super();
this.key = 'path/to/example.json';
}
}
module.exports = S3Example;
`
#### then from the index.js ####
`javascript
const S3Example = require('./s3example');
new S3Example().put('content here')
.catch(err=>console.log(err));
new S3Example().get()
.then(res => console.log(res));
`
$3
#### create a file called dbexample.js ####
`javascript
const Model = require('nealyip-aws-lambda-helper/model');
class DBExample extends Model{
constructor(){
super();
this.tableName = 'test.batch';
this.partitionKey = 'batch_id';
this.sortKey = 'user_id';
}
}
module.exports = DBExample;
`
#### then from the index.js ####
`javascript
(new DBExample).scan()
.then(res => console.log(res.Items));
(new DBExample).createItem(
{
'id':1,
'name':2,
'value':3
}
).then(res=> console.log('success'), err=>console.log(err));
`
#### updateItem ####
For updateItem, you must provide the partition key and sort key (if there exists).
#### updateItem conditionally ####
`javascript
// Error will be thrown if the condition does not match
(new DBExample).updateItem(
{
'id':1,
'name':2,
'value':3
},
[['name', '=', '2'], ['value', 'begins_with', '4']]
).then(res=> console.log('success'), err=>console.log(err));
`
#### updateItem for number increment ####
`javascript
(new DBExample).updateItem(
{
'batch_id':1
},
[],
{
'value' : 5
}
).then(res=> console.log('success'), err=>console.log(err));
`
Increment in conjunction with conditions
`javascript
(new DBExample).updateItem(
{
'batch_id':1
},
[['gender', '=', 'F']],
{
'value' : 5
}
).then(res=> console.log('success'), err=>console.log(err));
`
#### updateItem with removing keys ####
`javascript
(new DBExample).updateItem(
{
'batch_id':1
},
[],
{},
['keytoremove1', 'keytoremove2']
).then(res=> console.log('success'), err=>console.log(err));
`
#### query with index ####
dbexample.js
`javascript
const Model = require('nealyip-aws-lambda-helper/model');
class DBExample extends Model{
constructor(){
super();
this.tableName = 'test.batch';
this.partitionKey = 'batch_id';
this.sortKey = 'user_id';
this.indexName = 'abc-index';
this.projectionExpression = 'abc,def,ghi';
}
}
module.exports = DBExample;
`
`javascript
(new DBExample).query([['abc', '>', '1234'],['def', '=', '4444'],['ghi', 'between', ['2222','4444']]])
.then(res => console.log(res.Items));
`
$3
#### create a file called funa.js ####
`javascript
class Funa extends Lambda {
constructor() {
super();
this.function = 'some-function-example';
// this.region = 'some region' // you can also specify the region for the function whenever the target is in a different region
}
}
module.exports = Funa;
`
`
The function name will auto be prepended with the ENV variable plus a hyphen side
eg, dev-some-function-example
If you want to override this, simply override the func getter
`
`javascript
class Funa extends Lambda {
constructor() {
super();
this.function = 'some-function-example';
}
get func(){
return this.function;
}
}
`
To invoke the function simply call the invoke method
`javascript
let a = new Funa();
a.invoke({
a:1,
b:2
});
// or
a.invokeAsync({
a:1,
b:2
});
`
$3
`javascript
const Crypto = require('nealyip-aws-lambda-helper/crypto');
// generate key and save
console.log(Crypto.genKey());
//encrypt data
let enc = new Crypto(key).encrypt('data');
// decrypt data
new Crypto(key).decrypt(enc);
`
// sha256 hash
new Crypto(key).hash('string')
$3
Encrypt with AES-GCM
`javascript
const crypto2 = require('nealyip-aws-lambda-helper/crypto2');
const encryptKey = Buffer.from('abcdefghijklmnop');
const aesgcm = new crypto2.AESGCM(encryptKey);
const plainText = Buffer.from('\u6211');
const aad = Buffer.from('something to be verified');
const result = aesgcm.encrypt(plainText, aad);
console.log(result.hex); // An object containing nonce, tag, cipher_text and cipher_suite in hex
console.log(result.base64); // An object containing nonce, tag, cipher_text and cipher_suite in base64
console.log(result.urlencoded); // A url-encoded string containing nonce, tag, cipher_text and cipher_suite
`
Decrypt with AES-GCM
`javascript
const crypto2 = require('nealyip-aws-lambda-helper/crypto2');
const encryptKey = Buffer.from('abcdefghijklmnopabcdefghijklmnop');
const aesgcm = new crypto2.AESGCM(encryptKey);
const aad = Buffer.from('something to be verified');
const encrypted = {
nonce: Buffer.from('ffd2eed848a2416f32915fae', 'hex'),
cipher_text: Buffer.from('d344db', 'hex'),
tag: Buffer.from('085eda92945103915be8c5ae57d0a835', 'hex')
};
const result = aesgcm.decrypt(encrypted, aad);
`
Encrypt with AES-CBC With RSA-SHA256
`javascript
const crypto2 = require('nealyip-aws-lambda-helper/crypto2');
const fun = async () => {
const privateKey = Buffer.from(await getFile('./test/keys/rsa_private.pem'));
const encryptKey = Buffer.from('abcdefghijklmnopabcdefghijklmnop');
const plainText = Buffer.from('\u6211');
const publicKey = Buffer.from(await getFile('./test/keys/rsa_public.pem'));
const signatureAlgorithm = new crypto2.RSAWithSha(privateKey, publicKey);
const aescbc = new crypto2.AESCBCWithSignature(encryptKey, signatureAlgorithm);
return aescbc.encrypt(plainText);
};
fun().then(result => {
console.log(result.hex);
console.log(result.base64);
}).catch(console.error);
``
Encrypt with AES-CBC With HMAC-SHA256
`javascript
const crypto2 = require('nealyip-aws-lambda-helper/crypto2');
const signKey = Buffer.from('hello');
const encryptKey = Buffer.from('abcdefghijklmnop');
const plainText = Buffer.from('\u6211');
const signatureAlgorithm = new crypto2.HMACWithSha(signKey);
const aescbc = new crypto2.AESCBCWithSignature(encryptKey, signatureAlgorithm);
const result = aescbc.encrypt(plainText);
console.log(result.hex);
console.log(result.base64);
``
Decrypt with AES-CBC With RSA-SHA256
`javascript
const crypto2 = require('nealyip-aws-lambda-helper/crypto2');
const fun = async () => {
const encrypted = {
nonce: Buffer.from('jGzj5DV2feQXKiRl3eGIWA==', 'base64'),
cipher_text: Buffer.from('bgtz/EFaBmRVauBDi0Vk1g==', 'base64'),
tag: Buffer.from('cMDdfPrkGdOX5pAmDazMJZGa53nwP7mUR475KECY06m4BCvgtJr6rVUrR6NTHM404M6Wz7+tshCBrEQYrVdByrlx8BbIWb7KU7h08QVLMBgVpbTRNExeXhRWzr6WeZniANNJ6dECqp9hbmnS7xpKGkR4ge1p8lyhNxIlmIikX4I/Z3yOy38KhT/13f1HtnHTpODlvnaZUVATx0W1eyHney9Itg/xxiBbdv6j7aFgRkDcdvIFMJbu0ZYYspsCas1rOmuK0tTMYmbjXsv1WwOzfNS9bSQQim36op08WXy62txdaR9OlHM8Lu8/3F9al7YWxaIHMq8XE2fvzM1Cw8om/Q==', 'base64')
};
const privateKey = Buffer.from('');
const encryptKey = Buffer.from('abcdefghijklmnopabcdefghijklmnop');
const publicKey = Buffer.from(await getFile('./test/keys/rsa_public.pem'));
const signatureAlgorithm = new crypto2.RSAWithSha(privateKey, publicKey);
const aescbc = new crypto2.AESCBCWithSignature(encryptKey, signatureAlgorithm);
return aescbc.decrypt(encrypted);
};
fun().then(result => {
console.log(result.toString('utf-8'))
});
``
$3
`javascript
const https = require('./https');
https.json({
url : 'https://www.example.com/auth',
method: 'post',
data : {
user : 'helloabc',
password: 'abcdefgh'
}
})
.then(res => res.body)
.then(res => JSON.parse(res).token)
.then(token => https.json({
url: 'https://www.example.com/dosth',
method: 'get',
headers : {
Authorization: 'Bearer ' + token
}
}
))
.then(res => res.body)
.then(console.log, err => console.log('Error: ' + err.message));
`
$3
`javascript
const helpers = require('nealyip-aws-lambda-helper/helpers');
console.log(helpers.uniqid());
`
$3
`javascript
const helpers = require('./helpers');
console.log(helpers.utcAdd(2, 'minute'));
console.log(helpers.utcAdd(2, 'day'));
console.log(helpers.utcAdd(2, 'second'));
console.log(helpers.utcAdd(2, 'hour'));
console.log(helpers.utcAdd(2, 'month'));
`
$3
`javascript
let helpers = require('nealyip-aws-lambda-helper/helpers');
console.log(helpers.utcNow()); //2017-11-01T12:20:20.000Z
`
$3
`javascript
let helpers = require('nealyip-aws-lambda-helper/helpers');
console.log(helpers.isPast('2017-11-01T19:14:00.000+0800'));
`
$3
`javascript
let helpers = require('nealyip-aws-lambda-helper/helpers');
console.log('toUTC', helpers.toUTC('2017-11-01 00:12', 'Asia/Hong_Kong'));
console.log('toUTC', helpers.toUTC('2017-11-01 13:12', 'Asia/Hong_Kong'));
`
$3
`javascript
let moment = require('nealyip-aws-lambda-helper/moment-with-timezone.min');
console.log(moment().tz('Asia/Tokyo').format('YYYYMMDD HH:mm:ss'));
`
$3
`javascript
let helpers = require('nealyip-aws-lambda-helper/helpers');
console.log(helpers.rangeForMonth('2017-11')); // ['2017-11-01', '2017-11-02',...... '2017-11-30']
`
$3
`javascript
const Response = require('nealyip-aws-lambda-helper/response');
exports.handler = (event, context, callback) => {
let response = new Response(event, callback, 'POST');
response.ok({
data : '1234'
});
}
`
Tips: response.checkInput() can be used to check event input and reject the request for invalid input
$3
`javascript
const Response = require('nealyip-aws-lambda-helper/response-with-cors-xsrf.js');
const CustomError = require('nealyip-aws-lambda-helper/error').CustomError;
exports.handler = (event, context, callback) => {
let response = new Response(event, callback, 'POST');
response.checkInput()
.then(() => {
// do something
})
.then(() => response.ok({
data : '1234'
}))
.catch(error => response.fail({error: error.message}, error instanceof CustomError ? error.httpCode : 500));
}
`
Tips: You can extend the Response class and checkInput() method for any custom validation
#### Send response cookie ####
`javascript
const Response = require('nealyip-aws-lambda-helper/response');
exports.handler = (event, context, callback) => {
let response = new Response(event, callback, 'POST');
response.ok({
data : '1234'
}, 'SESSIONID=abcd; path=/; HttpOnly');
}
`
Multiple cookie was supported by AWS on oct 2018
`javascript
const Response = require('nealyip-aws-lambda-helper/response');
exports.handler = (event, context, callback) => {
let response = new Response(event, callback, 'POST');
response.ok({
data : '1234'
}, ['SESSIONID=abcd; path=/; HttpOnly', 'CSRF_TOKEN=12345; path=/;']);
}
`
$3
`javascript
const cookie = require('nealyip-aws-lambda-helper/cookie');
try{
let result = cookie.parse('SESSIONID=abcd; some=cookie; another=cookie');
console.log(result['SESSIONID']);
} catch (e) {
console.log(e.message);
}
`
$3
#### To find the lambda function for an arn ####
`javascript
const ARNHelper = require('nealyip-aws-lambda-helper/arn-helper');
new ARNHelper('some arn')
.functionName()
.then(fn => console.log(the lambda function for ${arn} is ${fn}));
`
#### To get all resources from API gateway ####
`javascript
const ARNHelper = require('nealyip-aws-lambda-helper/arn-helper');
new ARNHelper()
.getAllResources()
.then(console.log); // {items : [{},{}]}
`
$3
`
npm install --save nealyip-aws-lambda-helper
`
You are required to provide 2 env variables
`
S3BUCKET : your-bucket
ENV : dev
`
The ENV is the dynamodb prefix
for example
if the dynamodb is dev.test.batch
then the ENV will be dev
and the model table name
this.tableName = 'test.batch';
$3
To build the moment-with-timezone.js
`npm
npm install
npm run build-prod
npm publish
`
To build the dist
`npm
npm run build-ts
`
To publish release
inside dist folder
`npm
npm publish
`
`npm
npm publish --tag beta
npm dist-tag ls
`
Fix wrong dist-tag
`npm
npm dist-tag add nealyip-aws-lambda-helper@1.0.65 latest
``