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");
}
});
});
Related
So on the React Native side the console.log is printing this for the image file as in I'm doing console.log(photos[1]) and getting this
{"fileName": "rn_image_picker_lib_temp_0d752f09-0fab-40f0-8c89-13dec3695de0.jpg", "fileSize": 374466, "height": 810, "type": "image/jpeg", "uri": "file:///data/user/0/com.cheersfe/c
ache/rn_image_picker_lib_temp_0d752f09-0fab-40f0-8c89-13dec3695de0.jpg", "width": 1000}
Here is my React Native Code
const createFormData = (photos, body = {}) => {
const data = new FormData();
if (photos.length > 1) {
console.log(photos[1])
data.append("images", photos[1]);
}
Object.keys(body).forEach((key) => {
data.append(key, body[key]);
});
return data;
};
const onAddButtonClick = () => {
if (value === null) {
Alert.alert("Hold On!", "Please select a goal");
} else if (descriptionText === "") {
Alert.alert("Hold On!", "Update description required");
}
setLoading(true);
const body = createFormData(photos, { join_goal: value, body: descriptionText });
postGoalUpdatePost(body).then(response => {
// navigation.navigate("PostsScreen");
setLoading(false);
}).catch(error => {
const errorMessage = `${error.name}: ${error.message}`;
});
setLoading(false);
};
export async function postGoalUpdatePost(body) {
return constructConfig().then(config => {
return axios.post(`${url}/posts/update`, body, config).then(response => {
return response.data;
});
});
}
But on the Django side when I look at request.data['images'] I get this crazy hexstring:
\x7f.x�������uJr|�����a=e��|�\x00��^�=J0�^������\x08\x1a\\\x02;�H�a�a�\x19=�u�K\x01�x䞧�\x0e�{{�\x07\x14���}H�2\x06?.)%�\x7f\x1f�\x0c�RvI������=H-���[��䌏ÿ^��\x00玵�$��<g�\x1d}�\x1d�\x00®7�\x1e���Yr\x7f�\x1f���+&��wт�I�?������$�Ӯz���N?Z�+�\x07�Oo\x7f�?����\x7f\x13���ܒ1����\r����V=J0M�\x7f5�I5�ϹVG���\x189��`�\x7fJ�$��u�1���{\x7f.�չ:7���kuO��\x15���m,����{\x18x�\x7f.]�\x7f�W��s�\x0e=��1�\x00֬�e^��0y$sӧ�\x0ez՛���\x7f3YS\x13��|��+�\x7f\x13��#���;>�k�o�\x7fñ\x1c�\x03�\x0f\x18�;s�\'��ߥ\x19$$�{���O���SI�\x1b�U\x1f�\x0f�O�\x15���}^����֥\x08���u���\x002��|����|���Y�$�\x003�^�A�9�>�j��\x1f����z\x1f��U��\x17�u=z\x10\\��O����b9�V\x18\x04p\x08������Vd�G\x1f��2O�V��\x1f�ک\\u?C��qԛJI[���zT"����_�W+�\x02\x06\x0f$u����\x00����\x15\x19�\x1f��4W\x0b��z$w���'
so clearly it's coming in as a string rather than a file. How do I fix this?
The issue was the format that the upload library was saving the json
{"fileName": "rn_image_picker_lib_temp_0d752f09-0fab-40f0-8c89-13dec3695de0.jpg", "fileSize": 374466, "height": 810, "type": "image/jpeg", "uri": "file:///data/user/0/com.cheersfe/c
ache/rn_image_picker_lib_temp_0d752f09-0fab-40f0-8c89-13dec3695de0.jpg", "width": 1000}
needs to be in
{'name': file_name, 'uri': uri, 'type': type}
format. Then needed 'content-type' to be 'multipart/form-data'
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;
});
I have the following model in LoopBackJS:
{
"name": "member",
"base": "PersistedModel",
"properties": {
"firstName": {
"type": "string"
}
"public": {
"type": "boolean"
}
},
"relations": {
"spouse": {
"type": "hasOne",
"model": "spouse",
"foreignKey": "spouseId"
}
}
}
Now I need to modify the firstName field, so one can only see "public": true members first name and the others gets firstName: "*". The function for that I have already.
But how can I access the data on each data-access-request?
I tried it with the with the operation hook e.g. find, findOne,... but when I miss one of them some users could access the firstName.
With the remote hook it's the same.
Now I'm trying it with the connector hook:
connector.observe('after execute', function(ctx, next) {
if (ctx.model === 'familyMember') {
if (ctx.req.command === 'find') {
}
}
next();
});
For all find queries (mongodb) but there I can't access the data. Is there a way to access those data? Or is there a much better (build-in) solution for this problem?
You need to check result after each remote :
member.afterRemote('**', function(ctx, modelInstance, next) {
if (ctx.result) {
if (Array.isArray(modelInstance)) {
var answer = [];
ctx.result.forEach(function (result) {
if(result.public === false)
result.firstName = "*";
answer.push(result);
});
} else {
var answer =ctx.result;
if(answer.public === false)
answer.firstName = "*";
}
ctx.result = answer;
}
next();
});
I can create a loopback model from an example json instance as shown here https://docs.strongloop.com/display/public/LB/Creating+models+from+unstructured+data. But from there is there an API to create the .json file in common/models?
#BoLaMN from Looback Gitter said this:
try app.registry.modelBuilder.introspect(json); that should give you a properties object. Then just add name, base to it and fs.writeSync JSON.stringify(obj).
I haven't tried yet, but it makes sense.
I've been using this:
var User = db.buildModelFromInstance('User', user, {idInjection: true});
var UserModel = (loopback.getModel(User));
var UserModelJSON = {}
UserModelJSON.name = 'User';
UserModelJSON.base = 'PersistedModel';
UserModelJSON.properties = UserModel.definition.rawProperties;
console.log(JSON.stringify(UserModelJSON));
fs.writeFile('User.json', 'UserModelJSON', function(err) {
if (err) throw err;
});
In your loopback /server directory at the root of your project, if you define the datasources.json file like so
{
"db": {
...
},
"restResourceName": {
"name": "restResourceName",
"baseURL": "http://restResourceUrl/",
"crud": true,
"connector": "rest"
}
}
And you define a boot script, like so
const fs = require('fs')
const path = require('path')
const writeInstance = (server, modelName, instance) => {
let Model = server.dataSources.restResourceName.buildModelFromInstance(modelName, instance)
let modelJson = Model.definition.toJSON()
delete modelJson.settings.base
fs.writeFile(path.join(__dirname, '..', 'models', modelName + '.json'),
JSON.stringify(modelJson, null, 2), (/*...*/) => {
/*...*/
})
}
module.exports = function (server) {
writeInstance(server, "Atom", {
atomicWeight: 6
})
}
You will generate a model file Atom.json
{
"name": "Atom",
"properties": {
"atomicWeight": {
"type": "Number"
},
"id": {
"type": "Number",
"id": 1,
"generated": true,
"updateOnly": true
}
},
"settings": {
"strict": false,
"forceId": "auto",
"replaceOnPUT": true
}
}
If you want to see the models in the loopback api explorer (swagger GUI), you must add the model to the model-config.json with a public: true property
{
"_meta": {
"sources": [
...
],
"mixins": [
...
]
},
"Atom": {
"public": true,
"dataSource": "restResourceName"
}
}
My api basically returns something like this:
GET /api/projects/
{
"count": 26,
"next": "http://127.0.0.1:8000/api/projects/?page=2",
"previous": null,
"results": [
{
"id": 21,
"name": "Project A",
...
},
{
"id": 19,
"name": "Project B",
...
},
...
]
}
Using NgResource, I am able to query the api and get the data like this:
var PROJECT = $resource('/api/projects/:id/', {id:'#id'},{
query : {
method : 'GET',
isArray : false
}
});
factory.project_list = function(callback) {
PROJECT.query({},function(project_list){
factory.project_list = project_list.results;
callback();
});
};
My different projects are now available in factory.project_list. The issue here is that each item in factory.project_list are not ngResource items. So I can't call methods such as .$save(), .$update()...
I saw a transformResponse() function but I'm not able to get it working easily...
Do you have any idea what could be the best approach here ?
This is what worked for me:
app.config(['$resourceProvider', function($resourceProvider) {
$resourceProvider.defaults.stripTrailingSlashes = false;
}]);
services.factory('Project', ['$resource',
function($resource) {
return $resource('api/project/:id/', {}, {
query: {
method: 'GET',
url: 'api/projects/',
isArray: true,
transformResponse: function(data, headers) {
return angular.fromJson(data).results;
},
},
});
}
]);