Ember and Postgresql(table values) to json format


#1

Helloo! I am having problems with the response of my queries sent to ember cli app. For example, I have my models:

//models/post.js
 import DS from 'ember-data';

 var attr= DS.attr;
 export default DS.Model.extend({
 author: DS.belongsTo('author'),

 title: attr('string'),
 body: attr('string'),
 date: attr('date')
});

//models/author.js
import DS from 'ember-data';

export default DS.Model.extend({
posts: DS.hasMany('post'),
name: DS.attr('string')
});

So ember expects a response in the following json format:

var posts= [
  {
    id: 1,
    title:'Bananas',
    author_id:1,
    date: new Date(2014,5,4,9,0,0),
    body:"mmm yum"
  },
   {
    id: 2,
    title:'Apples',
    author_id:1,
    date: new Date(2015,1,1,9,0,0),
    body: "Try these poison apples"
  }];

 var authors= [{
    id: 1,
    name: "George",
   posts:[1,2]
  }]

***My problem is if I am getting my information from a query using Postgresql, how do I send the resulting rows in that format, I have a table with the author_id and the post_id that the author posted. Help please, thanks!!!


#2

You are not reading data from postgresql using ember. You are using some server-side technology. This is where you need to convert your data into JSON.

Maybe if you told us what you are using, someone who uses the same could help you. So… what’d that be?


#3

Hii, I am using node js, example (HTTP GET):

app.get('/',isLoggedIn,function(req,res){
var client = new pg.Client(conString);
client.connect();

var query = client.query({
text : "SELECT * FROM post natural join event"
});

   query.on("row", function(row, result) {
result.addRow(row);
   });

query.on("end", function(result) {

var response = {
  'posts' : result.rows,
  'users': what goes here???  (array of post ids--> posts: [1,2,2...] (ids of posts that a specific user posted)
};
console.log(result.rows)
console.log(result.rows[0]['first_name']);
client.end();
res.json(response);
});

#4

I don’t know node.js unfortunately, but I believe JSON.stringify should be available? If so, you should use it to convert your data into JSON.


#5

You could use https://github.com/SeyZ/jsonapi-serializer if you are on node.