Hi, I need to create customize json format. I have used many to many relationships with user, tags and taggable. Please find the code below here.
User Controller
web/models.user_controller.ex
defmodule VampDev.UserController do
use VampDev.Web, :controller
def index(conn, _params) do
user =
VampDev.User
|> Repo.all()
|> Repo.preload(:tags)
json(conn, %{user: user})
end
end
User model
web/models.user.ex
defmodule VampDev.User do
use Ecto.Schema
use VampDev.Web, :model
@primary_key {:id, :string, []}
schema "users" do
field :name, :string
field :country, :string
many_to_many :tags, VampDev.Tag, join_through: "taggables"
end
end
This is json output
// 20171107045356
// http://localhost:4000/api/v1/users
{
"type": [
{
"tags": [
{
"name": "photo",
"id": "a7d41c25-0452-47eb-b400-7237b2ff2c6d"
}
],
"name": "Alberto Giubilini",
"id": "042807cc-26e1-4122-9235-23412eacaa79",
"country": "Singapore"
},
{
"tags": [
{
"name": "photo",
"id": "a7d41c25-0452-47eb-b400-7237b2ff2c6d"
}
],
"name": "Hannah Maslen",
"id": "0bdb2538-76c1-49b8-bee0-f27bbbfff8ae",
"country": "Hong Kong"
},
]
}
I have to customize the above json based upon the below Script .
JS in front end
<script>
let request = (method, path) => {
var headers = new Headers();
headers.append('Accept', 'application/vnd.api+json');
return fetch(new Request(`http://localhost:${path}`, {
method,
headers,
mode: 'cors',
cache: 'default'
}));
};
let get = (path) => { return request('GET', path) };
let put = (path) => { return request('PUT', path); };
let post = (path) => { return request('POST', path); };
(function init() {
get('/vamp_test.php').then(response => {
return response.json();
}).then(json => {
var includedMap = {};
json.included.forEach(item => {
if (!includedMap[item.type]) {
includedMap[item.type] = {};
}
includedMap[item.type][item.id] = item;
});
json.data.forEach(item => {
if (item.type && item.type.toLowerCase() === 'user' && item.relationships.taggables.data.length > 0) {
var tagsHtml = item.relationships.taggables.data.map(taggableRelationship => {
if (taggableRelationship && taggableRelationship.type === 'taggable') {
var taggable = includedMap[taggableRelationship.type][taggableRelationship.id];
if (taggable && taggable.relationships && taggable.relationships.tag && taggable.relationships.tag.data) {
var tag = includedMap[taggable.relationships.tag.data.type][taggable.relationships.tag.data.id];
if (tag) {
return `<span class="tag label label-default"">${tag.attributes.name}</span> `;
}
}
}
return '';
}).join('');
var name = item.attributes['full-name'];
var country = item.attributes.country || 'the earth';
$("#main-list").append(`<li class="list-group-item"><span class="name"><strong>${name}</strong> from ${country}</span><div class="tags">${tagsHtml}</div></li>`);
}
})
});
})();
</script>
I am getting the below error message whenever i run the page
Phoenix.NotAcceptableError at GET /api/v1/users
Exception:
How to fix this issue?