How to retrieve a name from the data in response in vuejs - html

I have a issue that i want to get the name from the response of api.
Here is what i have, i have response like this:
capabilities: (55) ["x:list", "y:create", "z:retrieve"]
created_at: "2021-03-09T14:13:18.214999Z"
test: null
description: "test"
What i want to that to have only get the "x:list" from the above
Here is what i am doing is:
this.response.data.data
Please help

I do not know how you process the data, so I cannot give an exact answer. I guess it would be something like this
const { capabilities } = this.response.data
const xList = capabilities.find(item => item === "x:list")
console.log(xList)

Related

return model instance without tuple when case statement is used in SQLAlchemy + FastAPI

Let's say I have an API, by calling it we get a list of posts, for each post I want to send a value whether that post is editable or not by the logged-in user in the response. so for that I'm using Case statement from SQLAlchemy and based on the logged-in user ID I'm returning true or false
The code looks like below
is_editable_expr = case(
[
(Post.user_id == current_user.id, True),
],
else_=False,
).label("is_editable")
data = db_session.query(Post, is_editable_expr).order_by(Post.created_at.desc()).join(User).all()
I'm using FastAPI and when it tries to serialize the data it fails because the value returned by this is ORM looks like
[(<Post title=Todo title description=A short description about your todo>, False), ...]
here the post model instance is inside the tuple and is_editable is directly accessible. the Post pydantic model looks like this
class Post(BaseModel):
id: int
title: str,
description: str,
user: User
is_active: bool
is_editable: bool
class Config:
orm_mode = True
since the orm instance itself is inside tuple while serializing it's failing and cannot access title/descriptions etc. I want my response to be a list of Post and it should look like this
[
{
"title":"title name",
"description":"some long description",
"is_editable":true
},
...
]
Can anyone please advice or suggest how can I make it work. Thanks in advance.
That is happening because of your query definition: db_session.query(Post, is_editable_expr)
So basically the second item in the tuple is your is_editable expression
I would rather avoid doing it in the database and would do a simple loop to do it on the server:
data = (db_session.query(Post)
.order_by(Post.created_at.desc())
.join(User)
.all())
for post in data:
post.is_editable = post.user_id == current_user.id

How to retrive children from a single object intead of array in json-server?

I am using json-server for mock-backend to retrive children form a single object.
The parent table sentinel and the child table sensor
As you can see the sensors is an array and sentinel is an object.
I have used http://localhost:3000/sentinel?_embed=sensors but the response is not what i am expecting, because I want sensors: [{id: 1}, {id: 2}, ecc]
The official documentation shows that are two ways to retrive two tables:
_embed (include children) and _expand (include parent).
How could I achive this result?
Given that sentinel is a single object in your db.json and you can't have more than one sentinel it is not clear to me how your query is different from retrieving all sensors with sentinelId=10:
/sensors?sentinelId=10
In fact if you try this API:
/sentinel/10/sensors
it will work, because json-server rewrite the url exactly to the previous query.
If for some reason you don't want to use the sentinel id directly in the query, the other option is to use json-server as a module and define a custom route with the logic you need. Here's a basic example that exposes a /sentinel/sensors API and retrieve sentinel data along with the sensors whose sentinelId equals to the current sentinel id:
const jsonServer = require('json-server');
const server = jsonServer.create();
const router = jsonServer.router('./db.json');
const db = router.db;
server.use(jsonServer.bodyParser);
server.get('/sentinel/sensors', (req, res) => {
const sentinel = db.get('sentinel').value();
const sensors = db
.get('sensors')
.filter({ sentinelId: sentinel.id })
.value();
res.send({ ...sentinel, sensors: sensors });
});
server.use(router);
server.listen(3001, () => {
console.log('Mock server is running on port ' + 3001);
});
That would give you a response like this:
{
"id": 10,
"name": "Sentinel",
"sensors": [
{
"id": 1,
"sentinelId": 10
},
{
"id": 2,
"sentinelId": 10
}
]
}
Here's a stackblitz

How to store n number of inputs into an array using mysql in express.js

Hi I a beginner to the web development
I wanted to accept n number of the instance(n is inputted by the user) from the user and then store those values in an array-like structure so that my frontend can have access to it. Can this be done using mysql ?. I was reading StackOverflow posts that mentioned that it is not a good idea to use MySQL for this. However I am already kind of deep into my project so I want to clarify this.
Is this feasible using MySQL?
I guess you want to store something like object or array of something
let's say that in your front end there is a form with input and button
where the input is Add More Columns and the input is value so in your backend you will get an array of objects like
[
{ question: '1', answer: 'Answer1' },
{ question: '2', answer: 'Answer2' },
{ question: '3', answer: 'Answer3' },
{ question: '4', answer: 'Answer4' }
]
you can make a table
id | userId | payload
where id is generated by SQL
userId that you injected in the token (or something else to relate the user with his payloads)
and payload that contains the information that you need to store
const saveUserPayLoads = async (req, res) => {
const { payloads } = req.body;
const { id } = req.user
const data = []
for(payload of payloads) data.push(DBModule.create({ payload: JSON.stringify(payload), userId: id }))
return res.status(201).json({
message: 'Done',
success: true,
data
})
}

Sequelize raw queries TextRow and getting data out of it

Given this query here,
let output = [];
const sql = `select * from coredb.account LIMIT ${offset},${limit}`;
let data = await sequelize.query(sql, null, {raw: true, type: sequelize.QueryTypes.SELECT});
data.forEach((item) => {
console.log(item['id'], item.id); // <-- output says "undefined, undefined"
});
the data variable is indeed hydrated with the right row data when using console.log to inspect it.
But, when I try to access the individual properties, they only ever come back as undefined. This TextRow object that Sequelize seems to return the result in doesn't seem to want to let me access then explicit rows.
Just curious what i'm missing here, am I missing an option?
I agree, Sequalize raw queries are not intuitive. You don't need the null or raw: true flag. Something like this should work:
let data = await sequelize.query(sql, {type: sequelize.QueryTypes.SELECT});
When I tried this, "data" was an array of two objects, each being the query result. So, the properties can be accessed by using index [0].... e.g.
data[0].forEach((item) => {
console.log(item['id'], item.id); // <-- output says "undefined, undefined"
});
Not yet sure WHY this occurs!
EDIT - it's because .query() should have only two arguments. Changing the call to: sequelize.query(sql, {raw: true, type: sequelize.QueryTypes.SELECT}) resulted in data being a single array (as expected).
Finally I was able to find the solution for it.
You just need to make a new array and push data into it by finding bases on key name like this:
suppose we have data in students object:
let finalArray = new Array();
for (var k in students ) {
finalArray.push(students[k])
}
console.log(finalArray) // Normal JSON array object :)
m.sequelize.query(sql, {
model,
mapToModel: true
})
.then(model => res.status(200).send(model))
.catch(error => res.status(400).send(error.toString())
})

Ember Data findAll() not populating models?

new to ember js, and working on an app using ember-data. If I test with same data using FixtureAdapter, everything populates in the html template ok. When I switch to RESTAdapter, the data looks like it's coming back ok, but the models are not being populated in the template? Any ideas? Here's the code:
App.Store = DS.Store.extend({
revision:12,
//adapter: 'DS.FixtureAdapter'
adapter: DS.RESTAdapter.extend({
url:'http://bbx-dev.footballamerica.com/builderapirequest/bat'
})
});
App.Brand = DS.Model.extend({
name: DS.attr('string'),
numStyles: DS.attr('string'),
vendorId: DS.attr('string')
});
App.BrandsRoute = Ember.Route.extend({
setupController:function(controller){
},
model:function(){
return App.Brand.find();
}
});
And here is the data coming back, but not being inserted into the template!
returnValue: [{numStyles:1, name:Easton, vendorId:6043}, {numStyles:1, name:Louisville Slugger, vendorId:6075},…]
0: {numStyles:1, name:Easton, vendorId:6043}
1: {numStyles:1, name:Louisville Slugger, vendorId:6075}
2: {numStyles:1, name:Rawlings, vendorId:6109}
3: {numStyles:7, name:BWP Bats , vendorId:6496}
4: {numStyles:1, name:DeMarini, vendorId:W002}
status: "ok"
And here is the template:
{{#each brand in model.returnValue }}
<div class="brand-node"{{action select brand}}>
<h2>{{brand.name}}</h2>
<p>{{brand.numStyles}} Styles</p>
</div>
{{/each}}
Any help would be greatly appreciated! I'm not getting any errors, and the data seems to be coming back ok, just not getting into the template. Not sure if the returned dataset needs "id" param?
I am also using the Store congfig to alter the find() from plural to singular:
DS.RESTAdapter.configure("plurals", {
brand: "brand"
});
The way the API was written, its expecting "brand" and not "brands"... maybe its something to do with this??
Thanks in advance.
You have stated:
Not sure if the returned dataset needs "id" param?
Yes you are guessing right, you data coming back from the backend need's an id field set. And if the id field name is different then id you should also define this in ember like so:
App.Store = DS.Store.extend({
revision:12,
//adapter: 'DS.FixtureAdapter'
adapter: DS.RESTAdapter.extend({
url:'http://bbx-dev.footballamerica.com/builderapirequest/bat'
}),
serializer: DS.RESTSerializer.extend({
primaryKey: function (type) {
return '_my_super_custom_ID'; // Only needed if your id field name is different than 'id'
}
})
});
I suppose your Fixtures have an id defined thus it works, right?
Note: you don't need to define the id field at all explicitly, ember add's automatically the id field to a model, so your model is correct.
Here a website that is still a WIP but can be good reference for this conventions
and as stated there:
The document MUST contain an id key.
And this is how your JSON should look like for a collection of records:
{
"brands": [{
"id": "1",
"numStyles": "1",
"name": "Easton",
"vendorId" :"6043"
}, {
"id": "2",
"numStyles": "4",
"name": "Siemens",
"vendorId": "6123"
}/** and so on**/]
}
Note: as you have shown you JSON root is called returnValue this should be called brand or brands if you are not adapting the plurals. See here for reference for the JSON root I'm talking about.
Hope it helps