...

/

Creating Songs

Creating Songs

Learn how to create songs at back-end when using JSON:API.

Adding songs at backend

The next operation we move to the backend is song creation.

Let’s add the following code in the songs controller.

Press + to interact
// app/controllers/bands/band/songs.js
import Controller from '@ember/controller';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';
import Song from 'rarwe/models/song';
import { inject as service } from '@ember/service';
import fetch from 'fetch';
export default class BandsBandSongsController extends Controller {
@tracked showAddSong = true;
@tracked title = '';
@service catalog;
@action
updateTitle(event) {
this.title = event.target.value;
}
@action
// saveSong() {
// let song = new Song({ title: this.title, band: this.model });
async saveSong() {
let payload = {
data: {
type: 'songs',
attributes: { title: this.title },
relationships: {
band: {
data: {
id: this.model.id,
type: 'bands'
}
}
}
}
};
let response = await fetch('/songs', {
method: 'POST',
headers: {
'Content-Type': 'application/vnd.api+json'
},
body: JSON.stringify(payload)
});
let json = await response.json();
let { id, attributes, relationships } = json.data;
let rels = {};
for (let relationshipName in relationships) {
rels[relationshipName] =
relationships[relationshipName].links.related;
}
let song = new Song({ id, ...attributes }, rels);
this.catalog.add('song', song);
this.model.songs = [...this.model.songs, song];
this.title = '';
this.showAddSong = true;
}
@action
cancel() {
this.title = '';
this.showAddSong = true;
}
}

This is a ...

Access this course and 1400+ top-rated courses and projects.