How to do Loopback in array query - loopbackjs

I have a table Conversation with property :
"participants": {
"type": [
"object"
],
"required": true
}
and the dataSource is MongoDb. I inserted data in format:
{participants:[{userId:1},{userId:2}]}.
Now I want to find all conversation which userId 1 is in.
What i did is using this filter: {where:{participants:{userId:1}}} but it doesn't work like MongoDb query. How can I achieve it?

you can try this:
app.models.Conversation.find({"where":{"participants":{"elemMatch":{"userId":1}}}}, function(err, res){
console.log(err, res)
})

Related

Postman JSON Schema Validation fails, if an Object.prototype function declared prior to the validation

I have a schema validation test in my postman collection, which validates if the response adhere to the schema. This is how I do it.
var schema =
{
"type": "object",
"properties": {
"data": {
"type": "object",
"properties": {....
}
pm.test("Schema Validation - TC001", function(){
pm.response.to.have.jsonSchema(schema);
});
When I execute just this script, it validates the schema of the response successfully.
However, in my postman collection I have declared a global function, prior to the schema validation, using Object.prototype() and I'm calling the function as _.funcABC("a","b","c")
Object.prototype.funcABC = function (var1, var2, var3) {
console.log("test");
}
And, my schema validation fails, when I run the entire collection.
While troubleshooting, I came across this, which indicates that the Object.prototype could interfere with JSONschema.
Is there a way to overcome this interference of Object.prototype() on JSONschema? So far, I couldn't find a workable solution.
Thanks.
What stops you from doing this:
pm.test('validate schema', function () {
let temp = Object.prototype.function1
delete Object.prototype.function1
pm.expect(ajv.validate(schema_response, response)).to.true;
Object.prototype.function1 = temp
})

AWS amplify graphql mutation: Cannot return null for non-nullable field

I am fairly new to both GraphQL and AWS amplify so this might be a newbie question.
I have defined the type listed below in schema.graphql. If I create a mutation using a type with id: ID!, I get a Cannot return null for non-nullable field Vocabulary.id.
How do I specify a field should be an identity field in AWS amplify graphql? specifying id: ID! for an identity field, in this AWS amplify workshop seems to work fine.
~\amplify\backend\api\vidaudtranscription\schema.graphql:
type Vocabulary #model
#key(fields:["userId"])
#auth(rules: [{allow: owner}])
{
id: ID!
userId: String!
vocabularies: [String!]!
}
Mutation Request:
mutation MyMutation {
createVocabulary(input: {userId: "abc", vocabularies: ["123", "456"]}) {
id
owner
userId
vocabularies
}
}
Mutation Response:
{
"data": {
"createVocabulary": null
},
"errors": [
{
"message": "Cannot return null for non-nullable field Vocabulary.id.",
"locations": [
{
"line": 5,
"column": 5
}
],
"path": [
"createVocabulary",
"id"
]
}
]
}
You must provide id in your input argument:
createVocabulary(input: {userId: "abc", vocabularies: ["123", "456"]})
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
The error is a bit hard to read but it contains all the information you need to decipher it:
"Cannot return null for non-nullable field Vocabulary.id." is complaining that Vocabulary.id (in the Vocabulary object you're creating) can't be null, but it is
"path": ["createVocabulary", "id"] is the location of the missing field, i.e. the "id" field in the createVocabulary structure
(I'm glossing over some of the details here. To be technically correct the error is from the resolver failing to serialize the response object, rather than interpret the input object. But if you provide the required fields in your input object the rest should work.)

Ember DS.hasMany children not showing up with JSON API

I am trying to use the JSON API Adapter with ember-cli 2.5.1 , but I'm having a bit of trouble.
I have a todo-list.js model, which has a "hasMany" relationship to todo-list-item.js. Getting the todo-list, the server returns this:
{
"links": {
"self": "http://localhost:4200/service/v1/todolists/b-tlst-af69786c-cbaf-4df9-a4a3-d8232677006a"
},
"data": {
"type": "todo-list",
"id": "b-tlst-af69786c-cbaf-4df9-a4a3-d8232677006a",
"attributes": {
"name": "b1-TodoList",
"created-on": 1468474962458,
"modified-on": 1468474962458
},
"relationships": {
"todolistitems": {
"data": {
"type": "todo-list-item",
"id": "b-todo-b5e3c146-d93a-4f97-8540-875bbcd156ca"
}
}
}
}
}
If there had been two TodoListItem children instead of one, the value of that "data" key would have been an array, rather than an object.
After receiving this, I was expecting the Ember Chrome plug-in's "Data" tab to show 1 TodoList and 1 child TodoListItem. Instead, it shows 1 TodoList and 0 TodoListItems.
I note from the Network tab that the browser never makes a request to get the items listed in the "data" section of the response.
Is the relationships section above correct and sufficient?
It turns out to have been caused by promise misunderstandings on the client side, and additionally, on the server I had to put dashes in the "relationships" key (i.e. "todo-list-items") and make the value of "data" an array.

CRUD operations using Ember-Model

Here,I am trying to implement CRUD operations using ember-model.
I am totally new to ember environment,actually i don't have much understanding of ember-model.
Here,i am trying to add new product and delete existing one.I am using inner node of fixture
i.e. cart_items.My this fixture contains two node i.e. logged_in and cart_items and this what my fixture structure :
Astcart.Application.adapter = Ember.FixtureAdapter.create();
Astcart.Application.FIXTURES = [
{
"logged_in": {
"logged": true,
"username": "sachin",
"account_id": "4214"
},
"cart_items": [
{
"id": "1",
"name": "Samsung Galaxy Tab 2",
"qty": "1",
"price": "100",
"subtotal": "100"
},
{
"id": "2",
"name": "Samsung Galaxy Tab 2",
"qty": "1",
"price": "100",
"subtotal": "100"
},
{
"id": "3",
"name": "Samsung Galaxy Tab 2",
"qty": "1",
"price": "100",
"subtotal": "100"
}
]
}
];
I want to this fixture struture only to get data in one service call from server.
Now,here is my code which i am using to add and delete product from cart_items
Astcart.IndexRoute = Ember.Route.extend({
model: function() {
return Astcart.Application.find();
}
});
Astcart.IndexController = Ember.ArrayController.extend({
save: function(){
this.get('model').map(function(application) {
var new_cart_item = application.get('cart_items').create({name: this.get('newProductDesc'),qty: this.get('newProductQty'),price: this.get('newProductPrice'),subtotal: this.get('newProductSubtotal')});
new_cart_item.save();
});
},
deleteproduct: function(product){
if (window.confirm("Are you sure you want to delete this record?")) {
this.get('model').map(function(application) {
application.get('cart_items').deleteRecord(product);
});
}
}
});
But when i am trying to save product i am getting an exception
Uncaught TypeError: Object [object global] has no method 'get'
And when i am trying to delete product i am getting an exception
Uncaught TypeError: Object [object Object] has no method 'deleteRecord'
Here,i also want to implement one functionality i.e. on every save i need to check if that product is already present or not.
If product is not present then only save new product other wise update existing product.
But i don't have any idea how to do this?
I have posted my complete code here.
Can anyone help me to make this jsfiddle work?
Update
I have updated my code here with debugs.
Here, i am not getting any exception but record is also not getting delete.
I am not getting what is happening here?
Can anyone help me to make this jsfiddle work?
'this' context changes within your save method. You need to use the 'this' of the controller and not the map functions. Try this:
save: function(){
var self = this;
self.get('model').map(function(application) {
var new_cart_item = application.get('cart_items').create({
name: self.get('newProductDesc'),
qty: self.get('newProductQty'),
price: self.get('newProductPrice'),
subtotal: self.get('newProductSubtotal')
});
new_cart_item.save();
});
}

Mocha Supertest json response body pattern matching issue

When I make an API call I want to inspect the returned JSON for its results. I can see the body and some the static data is being checked properly, but wherever I use regular expression things are broken. Here is an example of my test:
describe('get user', function() {
it('should return 204 with expected JSON', function(done) {
oauth.passwordToken({
'username': config.username,
'password': config.password,
'client_id': config.client_id,
'client_secret': config.client_secret,
'grant_type': 'password'
}, function(body) {
request(config.api_endpoint)
.get('/users/me')
.set('authorization', 'Bearer ' + body.access_token)
.expect(200)
.expect({
"id": /\d{10}/,
"email": "qa_test+apitest#example.com",
"registered": /./,
"first_name": "",
"last_name": ""
})
.end(function(err, res) {
if (err) return done(err);
done();
});
});
});
});
Here is an image of the output:
Any ideas on using regular expression for pattern matching the json body response?
There are two things you may consider in your tests: your JSON schema and the actual returned values. In case you're really looking for "pattern matching" to validate your JSON format, maybe it's a good idea to have a look at Chai's chai-json-schema (http://chaijs.com/plugins/chai-json-schema/).
It supports JSON Schema v4 (http://json-schema.org) which would help you describe your JSON format in a more tight and readable way.
In this question's specific case, you could use a schema as follows:
{
"type": "object",
"required": ["id", "email", "registered", "first_name", "last_name"]
"items": {
"id": { "type": "integer" },
"email": {
"type": "string",
"pattern": "email"
},
"registered": {
"type": "string",
"pattern": "date-time"
},
"first_name": { "type": "string" },
"last_name": { "type": "string" }
}
}
And then:
expect(response.body).to.be.jsonSchema({...});
And as a bonus: the JSON Schema supports regular expressions.
I asked this question early in my understanding of the framework. For anyone else who stumbles on this, I recommend using chai for assertion. This helped use regular expression for pattern matching in a much cleaner way.
Here is an example:
res.body.should.have.property('id').and.to.be.a('number').and.to.match(/^[1-9]\d{8,}$/);
I wrote lodash-match-pattern and it's Chai wrapper chai-match-pattern to handle just these sorts of assertions. It can handle what you described with regular expressions:
chai.expect(response.body).to.matchPattern({
id: /\d{10}/,
email: "qa_test+apitest#example.com",
registered: /./,
first_name: "",
last_name: ""
});
or use any of many included matchers and potentially ignore fields that don't matter
chai.expect(response.body).to.matchPattern({
id: "_.isInRange|1000000000|9999999999",
email: _.isEmail,
registered: _.isDateString,
"...": ""
});
I think chai uses excessively verbose syntax.
var assert = require('assert');
//...
.expect(200)
.expect(function(res) {
assert(~~res.body.id);
})
//...