55 lines
1.3 KiB
JavaScript
55 lines
1.3 KiB
JavaScript
import { Controller } from "@hotwired/stimulus"
|
|
|
|
/**
|
|
* @todo Handle errors
|
|
*/
|
|
export default class extends Controller {
|
|
static targets = [
|
|
'building',
|
|
'showBuilding',
|
|
'buildingName',
|
|
'buildingForm'
|
|
];
|
|
|
|
async submit(event) {
|
|
event.preventDefault();
|
|
|
|
if (event.currentTarget === this.buildingFormTarget) {
|
|
const options = this.prepare(
|
|
JSON.stringify({name: this.buildingTarget.value}),
|
|
'POST'
|
|
);
|
|
|
|
const res = await this.send('/project/create', options);
|
|
|
|
if (res.id) {
|
|
this.buildingTarget.setAttribute('data-id', res.id);
|
|
this.showBuildingTarget.classList.remove('is-hidden');
|
|
this.buildingNameTarget.textContent = res.name;
|
|
}
|
|
}
|
|
}
|
|
|
|
prepare(data, method) {
|
|
return {
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
},
|
|
body: data,
|
|
method,
|
|
}
|
|
}
|
|
|
|
/**
|
|
* @todo Return Exception on response error
|
|
* @param {string} endpoint
|
|
* @param {object} options
|
|
* @returns
|
|
*/
|
|
async send(endpoint, options) {
|
|
return await fetch(endpoint, options)
|
|
.then(res => res.json())
|
|
.catch(error => console.log(error));
|
|
}
|
|
}
|