Ejecuto una aplicación web de Flask donde tengo un modelo de dominio (este ejemplo Thing ) cuyas propiedades (por ejemplo rating ) podrían actualizarse a través de una solicitud HTTP PATCH. En mi configuración de desarrollo codifiqué la URL de la API donde se debe realizar la solicitud, pero esto se convierte en una aplicación autohospedada de código abierto, por lo que Flask debe generar y configurar la URL.
<script type="module"> import {Thing} from './things.js'; // This string must be available inside the Thing class // The {{ }} syntax with url_for is Flask/Jinja template style (server side) const API_URL = '{{ url_for('thing_update', id='{0}' }}'; let stars = document.querySelectorAll('.rating .star') stars.addEventListener('click', function(el){ // To create an object with object properties, like its id let thing = new Thing({{ thing.id }}); thing.rating = el.getAttribute('value'); }) </script>Mi módulo se parece a:
class Entity { _API_URL = ''; async update (data) { let response = await fetch(this._API_URL, { method: 'PATCH', headers: {'Content-Type': 'application/json;charset=utf-8'}, body: JSON.stringify(data) }) if (!response.ok) { throw new Error(`Server response ${response.status}: `) } else if (response.status == 204) { console.debug('Response success, no content') return true } else { let json = await response.json() console.debug('Response success, body content: ', json) return json } } } class Thing extends Entity { _id = null; _rating = null; constructor(id) { super() this._id = id // How to get the proper API URL here??? this._API_URL = super._API_URL.format(id) } set rating(value) { this._rating = value this.update() } async update() { console.debug('Update rating to ' + this._rating) super.update({rating: this._rating}) } } export {Thing}Tengo experiencia en la codificación del lado del servidor (php/python, etc.) y se siente "incorrecto" establecer la URL de la API a través del método constructor o setter en la instancia del objeto. Esto debería ser algo tan constante en el nivel de clase.
Sin embargo, debido a que uso Flask y no uso javascript para un SPA o algo así, me cuesta trabajo hacer esto "bien". ¿Existe alguna práctica recomendada para este caso?