Loopback : Validate model from another model is not returning proper error message - validation

I am validating model from another model like below
Model.addFavorite = function (data, callbackFn) {
if (data) {
var faviroteModel = this.app.models.Favorite;
var objFavorite = new faviroteModel(data);
objFavorite.isValid(function (isValid) {
if (isValid) {
callbackFn(null, objFavorite);
}
else {
callbackFn(objFavorite.errors);
}
});
}
else callbackFn("Post data required", {});
}
If i do this then I am getting error like below
{
"error": {
"statusCode": 500,
"t": [
"is not a valid date"
]
}
}
It should be with error message like below
{
"error": {
"statusCode": 422,
"name": "ValidationError",
"message": "The `Favorite` instance is not valid. Details: `t` is not a valid date (value: Invalid Date).",
"details": {
"context": "Favorite",
"codes": {
"t": [
"date"
]
},
"messages": {
"t": [
"is not a valid date"
]
}
}
}
}
Can anyone tell me what am i missing here.
How can i achieve this.

https://github.com/strongloop/loopback-datasource-juggler/blob/master/lib/validations.js#L843
You might run into situations where you need to raise a validation
error yourself, for example in a "before" hook or a custom model
method.
if (model.isValid()) {
return callback(null, { success: true });
}
// This line shows how to create a ValidationError
var err = new MyModel.ValidationError(model);
callback(err);
}

Related

Remove null results from a array that can contain nullable values in GraphQL

I have a query in my app that works but response is little ugly, there is probably two ways to solve this:
Write resolver differently
Clean response from null values
Here is resolver:
t.list.field('manyDevices', {
type: 'Device',
description: 'Get list of devices belonging to user',
args: {
input: nonNull(deviceIdentifierInput.asArg()),
},
resolve: async (_, { input: { id } }, { prisma }) => {
return await prisma.device.findMany({ where: { userId: id } });
},
});
This resolver looks for all devices with provided id. Id can be mine and also can be from a some other user. Devices can be public and private, and I don't want to receive private devices except if they are mine.
const isDevicePublic = rule({ cache: 'strict' })(
async ({ isPublic }: Device) => {
if (!isPublic) {
return permissionErrors.noPermission;
}
return true;
},
);
const isDeviceOwner = rule({ cache: 'strict' })(
async ({ userId }: Device, _, { user }: Context) => {
assertValue(user, permissionErrors.noAuthentication);
if (userId !== user.id) {
return permissionErrors.noPermission;
}
return true;
},
);
These are rules that I place on my schema with graphql-shield library and it works. There is just one problem, if a user have a private device it will be listed in response array as null and graphql-shield will throw error, so response can look like this:
{
"errors": [
{
"message": "You have no permission to access this resource",
"locations": [
{
"line": 3,
"column": 5
}
],
"path": [
"manyDevices",
0,
"name"
],
"extensions": {
"code": "INTERNAL_SERVER_ERROR",
"exception": {
"stacktrace": [
"Error: You have no permission to access this resource",
" at Rule.resolve (/workspace/node_modules/graphql-shield/dist/rules.js:33:24)",
" at runMicrotasks (<anonymous>)",
" at processTicksAndRejections (internal/process/task_queues.js:93:5)",
" at async Promise.all (index 0)"
]
}
}
}
],
"data": {
"manyDevices": [
null,
{
"name": "device-01"
}
]
}
}
So there is one fetched device and other that is private that throws this error, can I somehow remove null and error response or should I filter them out in resolver?

does reportStateAndNotification support multiple device state reporting?

I am trying to report the status of a couple of devices via API and I am getting this error
Request payload:
{
"requestId":"3310672920401175639",
"agentUserId":"5d8f3dd42ce05140dc1c6a20",
"payload":{
"devices":{
"states":[
{
"5de28e041729ec0cb40ba906":{
"on":true
}
},
{
"5df49862f53ffa4c1452a448":{
"on":false,
"brightness":100
}
}
]
}
}
}
Response:
{
"error":{
"code":400,
"message":"Invalid JSON payload received. Unknown name "states" at 'payload.devices': Proto field is not repeating, cannot start list.",
"status":"INVALID_ARGUMENT",
"details":[
{
"#type":"type.googleapis.com/google.rpc.BadRequest",
"fieldViolations":[
{
"field":"payload.devices",
"description":"Invalid JSON payload received. Unknown name "states" at 'payload.devices': Proto field is not repeating, cannot start list."
}
]
}
]
}
}
can "states" hold more than one status of the device? or am I doing something wrong with this?
The states value in the payload should be an object with each unique device id as a key. It should not be returned with these wrapped into an array. So your request payload should look more like this:
{
"requestId":"3310672920401175639",
"agentUserId":"5d8f3dd42ce05140dc1c6a20",
"payload": {
"devices": {
"states": {
"5de28e041729ec0cb40ba906": {
"on": true
},
"5df49862f53ffa4c1452a448": {
"on": false,
"brightness": 100
}
}
}
}
}

GraphQL Mutation with JSON Patch

Are there any data types in GraphQL that can be used to describe a JSON Patch operation?
The structure of a JSON Patch operation is as follows.
{ "op": "add|replace|remove", "path": "/hello", "value": ["world"] }
Where value can be any valid JSON literal or object, such as.
"value": { "name": "michael" }
"value": "hello, world"
"value": 42
"value": ["a", "b", "c"]
op and path are always simple strings, value can be anything.
If you need to return JSON type then graphql have scalar JSON
which return any JSON type where you want to return it.
Here is schema
`
scalar JSON
type Response {
status: Boolean
message: String
data: JSON
}
type Test {
value: JSON
}
type Query {
getTest: Test
}
type Mutation {
//If you want to mutation then pass data as `JSON.stringify` or json formate
updateTest(value: JSON): Response
}
`
In resolver you can return anything in json format with key name "value"
//Query resolver
getTest: async (_, {}, { context }) => {
// return { "value": "hello, world" }
// return { "value": 42 }
// return { "value": ["a", "b", "c"] }
// return anything in json or string
return { "value": { "name": "michael" } }
},
// Mutation resolver
async updateTest(_, { value }, { }) {
// Pass data in JSON.stringify
// value : "\"hello, world\""
// value : "132456"
// value : "[\"a\", \"b\", \"c\"]"
// value : "{ \"name\": \"michael\" }"
console.log( JSON.parse(value) )
//JSON.parse return formated required data
return { status: true,
message: 'Test updated successfully!',
data: JSON.parse(value)
}
},
the only thing you need to specifically return "value" key to identify to get in query and mutation
Query
{
getTest {
value
}
}
// Which return
{
"data": {
"getTest": {
"value": {
"name": "michael"
}
}
}
}
Mutation
mutation {
updateTest(value: "{ \"name\": \"michael\" }") {
data
status
message
}
}
// Which return
{
"data": {
"updateTest": {
"data": null,
"status": true,
"message": "success"
}
}
}

Lambda and API gateway mapping

I want to return a value from handler to API gateway response header.
Handler.js
module.exports.handler = function(event, context, cb) {
const UpdateDate = new Date();
return cb(null, {
body: {
message: 'test'
},
header: {
Last-Modified: UpdateDate
}
});
};
s-function.json in "endpoints"
"responses": {
"400": {
"statusCode": "400"
},
"default": {
"statusCode": "200",
"responseParameters": {
"method.response.header.Cache-Control": "'public, max-age=86400'",
"method.response.header.Last-Modified": "integration.response.body.header.Last-Modified"
},
"responseModels": {
"application/json;charset=UTF-8": "Empty"
},
"responseTemplates": {
"application/json;charset=UTF-8": "$input.json('$.body')"
}
}
}
This can work. But I want to know how to use "integration.response.header.Last-Modified". Is my handler callback formate wrong?
Edit:
s-function.json in "endpoints"
"integration.response.header.Last-Modified" This doesn't work.
I want to know specific handler return formate to pass data to "integration.response.header.Last-Modified".
"responses": {
"400": {
"statusCode": "400"
},
"default": {
"statusCode": "200",
"responseParameters": {
"method.response.header.Cache-Control": "'public, max-age=86400'",
"method.response.header.Last-Modified": "integration.response.header.Last-Modified"
},
"responseModels": {
"application/json;charset=UTF-8": "Empty"
},
"responseTemplates": {
"application/json;charset=UTF-8": "$input.json('$.body')"
}
}
}
All of the output from your lambda function is returned in the response body, so you will need to map part of the response body to your API response header.
module.exports.handler = function(event, context, cb) {
const UpdateDate = new Date();
return cb(null, {
message: 'test',
Last-Modified: UpdateDate
});
};
will produce payload "{"message" : "test", "Last-Modified" : "..."}"
In this case you would use "integration.response.body.Last-Modified" as the mapping expression. As a side note, naming things "body" and "header" in your response body may make the mapping expressions confusing to read.
Thanks,
Ryan

How to create *static* property in can.Model

I need somehow to store metadata in the can.Model
I use findAll method and receive such JSON:
{
"metadata": {
"color": "red"
},
"data": [
{ "id": 1, "description": "Do the dishes." },
{ "id": 2, "description": "Mow the lawn." },
{ "id": 3, "description": "Finish the laundry." }
]
}
I can work with data like can.Model.List, but I need metadata like a static property or something.
You can use can.Model.parseModels to adjust your response JSON before it's turned into a can.Model.List.
parseModels: function(response, xhr) {
var data = response.data;
var metadata = response.metadata;
var properties;
if(data && data.length && metadata) {
properties = Object.getOwnPropertyNames(metadata);
can.each(data, function(datum) {
can.each(properties, function(property) {
datum[property] = metadata[property];
});
});
}
return response;
}
Here's a functional example in JS Bin: http://jsbin.com/qoxuju/1/edit?js,console

Resources