Major refactoring to include frontend...
This commit is contained in:
60
assets/controllers/form_controller.js
Normal file
60
assets/controllers/form_controller.js
Normal file
@@ -0,0 +1,60 @@
|
||||
import { Controller } from "@hotwired/stimulus"
|
||||
import API_CONFIG from "../config.js";
|
||||
|
||||
/**
|
||||
* @todo Handle errors
|
||||
*/
|
||||
export default class extends Controller {
|
||||
static targets = [
|
||||
'building',
|
||||
'showBuilding',
|
||||
'buildingName',
|
||||
'buildingForm'
|
||||
];
|
||||
|
||||
API_BASE = API_CONFIG.dev;
|
||||
|
||||
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(
|
||||
`${this.API_BASE}/api/buildings`,
|
||||
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));
|
||||
}
|
||||
}
|
||||
16
assets/controllers/hello_controller.js
Normal file
16
assets/controllers/hello_controller.js
Normal file
@@ -0,0 +1,16 @@
|
||||
import { Controller } from '@hotwired/stimulus';
|
||||
|
||||
/*
|
||||
* This is an example Stimulus controller!
|
||||
*
|
||||
* Any element with a data-controller="hello" attribute will cause
|
||||
* this controller to be executed. The name "hello" comes from the filename:
|
||||
* hello_controller.js -> "hello"
|
||||
*
|
||||
* Delete this file or adapt it for your use!
|
||||
*/
|
||||
export default class extends Controller {
|
||||
connect() {
|
||||
this.element.textContent = 'Hello Stimulus! Edit me in assets/controllers/hello_controller.js';
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user