API Hdr
Jump to navigation
Jump to search
Example API Handler
step for create lambdaFunction and Api handler
in app/src
- add lambda, copy LambdaFunction.js and change name. ex. CreateProduct_Main.js
Example:
'use strict';
const izaraSharedLib = require('@izara_project/izara-shared');
const dynamodbSharedLib = izaraSharedLib.dynamodbSharedLib;
const hash = require('object-hash');
//* require more module that you use
/**
* description of function.
* @param {string} type
* @param {string} name
*
* @returns {string} productId
*/
module.exports.createProduct = async (
_izContext,
type,
name
) => {
try {
_izContext.logger.debug('CreateProduct: ', {
type,
name
});
// ... do something
// **** example for code ****
//* create productId
let productId = hash({
type: type,
name: name
});
_izContext.logger.debug("productId: ", productId);
//* put record in ProductRecord table
await dynamodbSharedLib.putItem(
_izContext,
dynamodbSharedLib.tableName("ProductRecord"),
{ //keyValue
productId: productId //partition key
// no sort key
},
{ //add other attributes
attributes: {
type: type,
name: name
}
}
);
return productId
} catch (err) {
_izContext.logger.error('error CreateProduct: ', err)
throw (err)
}
}
//Local testing
async function test() {
const CorrelationIds = require('@izara_project/izara-core-library-correlation-ids');
const Logger = require('@izara_project/izara-core-library-logger');
const IntegrationTestDetail = require('@izara_project/izara-core-library-integration-tests/src/IntegrationTests')
let _izContext = {
correlationIds: CorrelationIds,
logger: Logger,
integrationTestDetail: IntegrationTestDetail
}
let type = "Clothes";
let name = "Dream";
return module.exports.updateCatalogSettings(
_izContext,
type,
name
)
}
test();
//** test => node CreateProduct_Main.js in terminal
- add lambda handler, copy LambdaFunctionHdrApi.js and change name ex. CreateProduct_HdrApi.js
Example: CreateProduct_HdrApi.js
'use strict';
const RBAC_TARGET_ID = process.env.iz_rbacTargetIdUser // iz_rbacTargetIdUser | iz_rbacDeliveryMethodId
const izara = require("@izara_project/izara-middleware");
const middleware = izara.middlewareHandler;
const createProduct = require('./CreateProduct_Main');
// not Authorizer : --------------------------------------------------------
// validate event params in middlewware before into function.
let validatorSchema = {
type: "object",
required: [
'body',
// 'requestContext'
],
properties: {
body: {
type: 'object',
// additionalProperties: false,
required: [
'type',
'name'
],
properties: {
type: {
type: 'string'
},
name: {
type: 'string'
}
}
}
}
};
// NOTE: not sure about remap_when_flatten and remove_when_flatten function of api still require for validate or not? Tam(19-Nov) -- Yes
// // for auth userLevel
// If not have Authorizer set setMiddlewareSettings.
middleware.setValidatorSchema(
validatorSchema,
//{ noAuthorizer: true }
);
// // // defalse user Authorizer.
// middleware.setValidatorSchema(validatorSchema)
module.exports.main = middleware.wrap(async (event, context, callback) => {
event._izContext.logger.debug('Event:', event);
try {
// invoke LambdaFunction
let createProductResponse = await createProduct.createProduct(
event._izContext, // correlationId/logger/integrationTestDetail/uniqueRequestId/userId
event.body.type,
event.body.name
);
// return error to client
if (createProductResponse instanceof Error) {
return (izara.response.failure(createProductResponse));
}
// return success to client
return (izara.response.success(createProductResponse));
} catch (err) {
event._izContext.logger.error('Error, CreateProduct_HdrApi: ', err);
return (izara.response.failure(err));
}
});
- function.yml
add lambda function For API handler
CreateProductApi:
handler: src/CreateProduct_HdrApi.main
name: ${self:custom.iz_resourcePrefix}CreateProductHdrApi
events:
- http:
path: CreateProduct
method: post
cors: true
# authorizer:
# arn: ${self:custom.iz_authorizerAppLevel}
# type: request
# resultTtlInSeconds: 0
iamRoleStatements:
- Effect: Allow
Action:
- dynamodb:PutItem
Resource:
- arn:aws:dynamodb:${self:custom.iz_region}:${self:custom.iz_accountId}:table/${self:custom.iz_resourcePrefix}Config
- arn:aws:dynamodb:${self:custom.iz_region}:${self:custom.iz_accountId}:table/${self:custom.iz_resourcePrefix}ProductRecord
** maybe should close lambda that don't want to deploy **
- core-function.yml
add role in resource of InitialSetup and InitialSetupTestEnv
resource:
- arn:aws:dynamodb:${self:custom.iz_region}:${self:custom.iz_accountId}:table/${self:custom.iz_resourcePrefix}Config
- arn:aws:dynamodb:${self:custom.iz_region}:${self:custom.iz_accountId}:table/${self:custom.iz_resourcePrefix}ProductRecord
- ${self:custom.iz_prefixIamRole}CreateProductApi${self:custom.iz_suffixIamRole} # eg. PutRolePolicy
// add more....