webarchi/assets/controllers/form_controller.js
Nicolò P 96bb0388a8 Include IFC file name
TODO: move UI routines to Stimulus
2025-04-02 17:31:28 +02:00

60 lines
1.5 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,
ifc: localStorage.getItem('loaded-ifc'),
}
),
'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));
}
}