How to validate json schema using avj and postman - postman

I'm trying to validate the following json that looks like this:
{
"errors": false,
}
using this on postman:
var Ajv = require('ajv'),
ajv = new Ajv({logger: console, coerceTypes: false}),
schema = {
"errors": {
"type": "number"
}
};
pm.test('Schema is valid', function() {
var error = pm.response.json()['errors'];
console.log("this is error: " +error);
pm.expect(ajv.validate(schema, {errors: error})).to.be.true;
});
pm.test('Schema is valid different way', function() {
var error = pm.response.json()['errors'];
console.log("this is error: " +error);
var validate = ajv.compile(schema);
pm.expect(validate(pm.response.json())).to.be.true;
});
but it's always passing, even though my errors object is a boolean and not a number. What am I doing wrong?
note: the logs look like this
this is error: false

You can check json schema using avj in Postman as follows:
var Ajv = require('ajv'),
ajv = new Ajv({logger: console}),
schema = {
"properties": {
"errors": {
"type": "boolean"
}
}
};
pm.test('Schema is valid', function() {
var error = pm.response.json()['errors'];
pm.expect(ajv.validate(schema, {errors: error})).to.be.true;
});
Data:
{
"errors": false
}
Result: Pass
Data:
{
"errors": true
}
Result: Pass
Data:
{
"errors": 123
}
Result: Fail
An alternate way
pm.test('Schema is valid', function() {
pm.expect(typeof(pm.response.json().errors) === "boolean").to.be.true;
});

Related

How to use where in condition in dynamodb filterexpression

I am learning dynamodb and I am trying how to fetch items with status 0 and 1 but when i write the below query, it is throwing error "Error ValidationException: Invalid FilterExpression: Syntax error; token: ":user_status_val", near: "IN :user_status_val". Could any one please help in fixing this issue.
const checkUserExists = (req) => {
return new Promise((resolve,reject) =>{
var searchParams = {};
if(req.body.email != ""){
searchParams = {
FilterExpression : "#email = :e AND #user_status IN :user_status_val",
ExpressionAttributeNames: {
"#user_status": "status",
"#email" : "email",
},
ExpressionAttributeValues: {
':user_status_val' : req.body.status,
':e' : req.body.email,
},
}
}
var params = {
Select: "COUNT",
TableName: 'register'
};
var finalParams = {...searchParams, ...params}
DynamoDB.scan(finalParams, function(err, data) {
if (err) {
console.log("Error", err);
} else {
console.log(data);
//res.send(data);
return resolve(data);
}
});
});
}

BatchWriteItemCommand with AWS.DynamoDB class using AWS SDK V3 in Nodejs

I have been trying for hours to perform a DynamoDB DeleteRequest using BatchWriteItemCommand but I keep getting the following error:
Error ValidationException: 1 validation error detected: Value null at 'requestItems.td_notes_sdk.member.1.member.deleteRequest.key' failed to satisfy constraint: Member must not be null
This is what my table looks like:
Partition key: user_id (string)
Sort key: timestamp (number)
DynamoDB Screenshot
This is what my code looks like:
// Import required AWS SDK clients and commands for Node.js
import {
DynamoDBClient,
BatchWriteItemCommand,
} from "#aws-sdk/client-dynamodb";
// Set the parameters
export const params = {
RequestItems: {
"td_notes_sdk": [
{
DeleteRequest: {
Item: {
Key: {
user_id: { S : "bb" },
timestamp: { N : 2 },
},
},
},
},
],
},
};
export const run = async () => {
const ddbClient = new DynamoDBClient({ region: "us-east-2" });
try {
const data = await ddbClient.send(new BatchWriteItemCommand(params));
console.log("Success, items inserted", data);
return data;
} catch (err) {
console.log("Error", err);
}
};
run();
Here are some resources that I've been trying to follow along with:
Resource 1: Writing items in Batch Example
Resource 2: AWS Javascript SDK v3 Documentation
Update: BatchWrite PutRequest work with the code below, so I know that the structure of my keys/attributes is closer to being correct. Still does not work for DeleteRequest.
export const params = {
RequestItems: {
"td_notes_sdk": [
{
PutRequest: {
Item: {
user_id: { "S": "bb" },
timestamp: { "N": "5" },
},
},
},
],
},
};
You don't supply an Item when deleting an item. You supply a Key.
Here is a working example:
const params_delete = {
RequestItems: {
"td_notes_sdk": [
{
DeleteRequest: {
Key: {
user_id: { S: "bb" },
timestamp: { N: "2" },
},
},
},
],
},
};
const delete_batch = async () => {
const ddbClient = new DynamoDBClient({ region: "us-east-2" });
try {
const data = await ddbClient.send(new BatchWriteItemCommand(params_delete));
console.log("Success, item deleted");
return data;
} catch (err) {
console.log("Error", err);
}
};
delete_batch();

Adding data to DynamoDB from the browser (CodePen) fails

I am new to AWS and got the following error when I tried to input data to the dynamodb invoking the lambda function between the 'API gateway' and the 'DynamoDB'.
Error:
Expected params.Item['Age'].S to be a string........
Screenshot of the Error:
Code:
I tried in the browser (CodePen) (I used the correct Invoke URL from the API gateway):
var xhr = new XMLHttpRequest();
xhr.open('POST', 'The API Invoke URL');
xhr.onreadystatechange = function(event){
console.log(event.target.response);
}
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({age: 26, height: 71, income: 2400}));
The following lambda function is invoked when running the above code from CodePen:
There I have imported the aws-sdk and dynamodb correctly.
exports.fn = (event, context, callback) => {
const params = {
Item: {
"UserId": {
S: "user_" + Math.random()
},
"Age": {
N: event.age
},
"Height": {
N: event.height
},
"Income": {
N: event.income
}
},
TableName: "compare-yourself"
};
dynamodb.putItem(params, function(err, data) {
if (err) {
console.log(err);
callback(err);
} else {
console.log(data);
callback(null, data);
}
});
};
In the above lambda function you can observe that I have formatted the inputs as numbers but in the API gateway, in the POST integration request I have converted the inputs to strings. so the data that is passed via the lambda function is already a string. No need to format by the Lambda function, again.
Body mapper in 'POST Integration-Request':
#set($inputRoot = $input.path('$'))
{
"age" : "$inputRoot.age",
"height": "$inputRoot.height",
"income": "$inputRoot.income"
}
I need to know the reason for the above error and am happy to provide any additional information required.
Thank you in advance.
Change the params to indicate that the value of the age field is "String" and not "Numeric":
const params = {
Item: {
"UserId": {
S: "user_" + Math.random()
},
"Age": {
"S": event.age # This was previously set to "N" which causes the issue
},
"Height": {
N: event.height
},
"Income": {
N: event.income
}
},
TableName: "compare-yourself"
};

JSON Validate check based on response from arrayElement

I wanted to check from the response format if status=AVAILABLE then arrayElement should return with roomTypeId else roomTypeId should not return for other status.
[
{
"status": "SOLDOUT",
"propertyId": "dc00e77f",
"Fee": 0,
"isComp": false
},
{
"roomTypeId": "c5730b9e",
"status": "AVAILABLE",
"propertyId": "dc00e77f",
"price": {
"baseAveragePrice": 104.71,
"discountedAveragePrice": 86.33
},
"Fee": 37,
"isComp": false
},
]
[
{
"status": "SOLDOUT",
"propertyId": "773000cc-468a-4d86-a38f-7ae78ecfa6aa",
"resortFee": 0,
"isComp": false
},
{
"roomTypeId": "c5730b9e-78d1-4c1c-a429-06ae279e6d4d",
"status": "AVAILABLE",
"propertyId": "dc00e77f-d6bb-4dd7-a8ea-dc33ee9675ad",
"price": {
"baseAveragePrice": 104.71,
"discountedAveragePrice": 86.33
},
"resortFee": 37,
"isComp": false
},
]
I tried to check this from below;
pm.test("Verify if Status is SOLDOUT, roomTypeId and price information is not returned ", () => {
var jsonData = pm.response.json();
jsonData.forEach(function(arrayElement) {
if (arrayElement.status == "SOLDOUT")
{
pm.expect(arrayElement).to.not.include("roomTypeId");
}
else if (arrayElement.status == "AVAILABLE")
{
pm.expect(arrayElement).to.include("roomTypeId");
}
});
});
You need to check if the property exists or not.
With the have.property syntax you can do that.
You can read the Postman API reference docs and also Postman uses a fork of chai internally, so ChaiJS docs should also help you.
Updated script:
pm.test("Verify if Status is SOLDOUT, roomTypeId and price information is not returned ", () => {
var jsonData = pm.response.json();
jsonData.forEach(function(arrayElement) {
if (arrayElement.status === "SOLDOUT") {
pm.expect(arrayElement).to.not.have.property("roomTypeId");
} else if (arrayElement.status === "AVAILABLE") {
pm.expect(arrayElement).to.have.property("roomTypeId");
}
});
});

Getting AWS Dynamodb query result as internel server error code : 502

This is my table "odo":
I want to retrive data where deviceId == 'A233' Between two timestamps. I run query inside Lamda Function and testing with API Gateway.
This is query I ran to get the result:
var params = {
TableName: "odo",
KeyConditionExpression: "#deviceId = :deviceIdVal AND #timestamp BETWEEN :sdate AND :edate",
ExpressionAttributeNames: {
"#deviceId": "deviceId",
"#timestamp": "timestamp"
},
ExpressionAttributeValues: {
":deviceIdVal": 'A233',
":sdate": 1110601808,
":edate": 1522902606
}
};
But I get a error as "Internal Server Error" and Error Code : 502
Why this query won't work? What am I missing?
When I ran another query using id field,it work.
module.exports.handler = function (event, context, callback) {
console.log(event);
let _response = "";
let invalid_path_err = {
"Error": "Invalid path request " + event.resource + ', ' +
event.httpMethod
};
if(event.resource === '/odos' && event.httpMethod === "GET"){
var params = {
TableName: "odo",
KeyConditionExpression: "#id = :id",
ExpressionAttributeNames: {
"#id": "id"
},
ExpressionAttributeValues: {
":id": 7
}
};
docClient.query(params, function(err, data) {
if (err) {
console.error("Unable to query. Error:", JSON.stringify(err, null, 2));
} else {
console.log("Query succeeded.",data);
_response = buildOutput(200, data);
return callback(null, _response);
}
});
}
else {
_response = buildOutput(500, {"error 500" : "invalid_path_err"});
return callback(_response, null);
}
};
/* Utility function to build HTTP response for the microservices output */
function buildOutput(statusCode, data) {
let _response = {
statusCode: statusCode,
headers: {
"Access-Control-Allow-Origin": "*"
},
body: JSON.stringify(data)
};
return _response;
};
This is the success result in test method execution in API Gateway:
The problem is that your query is trying to use a table partition key of deviceid and a range key of timestamp. In fact you have a parition key called id and no range key.
You can only use KeyConditionExpression on attributes that are a key, which in your case is the attribute id.
To do your 'query' you need to change KeyConditionExpression to FilterExpression and change query to scan
EDIT:
module.exports.handler = function (event, context, callback) {
console.log(event);
let _response = "";
let invalid_path_err = {
"Error": "Invalid path request " + event.resource + ', ' +
event.httpMethod
};
if(event.resource === '/odos' && event.httpMethod === "GET"){
var params = {
TableName: "odo",
FilterExpression: "#deviceId = :deviceIdVal AND #timestamp BETWEEN :sdate AND :edate",
ExpressionAttributeNames: {
"#deviceId": "deviceId",
"#timestamp": "timestamp"
},
ExpressionAttributeValues: {
":deviceIdVal": 'A233',
":sdate": 1110601808,
":edate": 1522902606
}
};
docClient.scan(params, function(err, data) {
if (err) {
console.error("Unable to query. Error:", JSON.stringify(err, null, 2));
} else {
console.log("Query succeeded.",data);
_response = buildOutput(200, data);
return callback(null, _response);
}
});
}
else {
_response = buildOutput(500, {"error 500" : "invalid_path_err"});
return callback(_response, null);
}
};
/* Utility function to build HTTP response for the microservices output */
function buildOutput(statusCode, data) {
let _response = {
statusCode: statusCode,
headers: {
"Access-Control-Allow-Origin": "*"
},
body: JSON.stringify(data)
};
return _response;
};