Hi everyone and sorry for maybe this dumb question, i'm working with javascript modules and trying to organize everything in order to be easier to use for my jr programmers since we are all kinda new to javascript not Jquery framework programming, so the thing is:
I created a module which is a helper for fetch data from rest services called Router:
const BaseUrl = 'http://localhost:1128'
/**
*
* Falta Mejorar la función para los siguientes escenarios:
* 1) Que se elija la ruta desde un modulo que tenga ya prefabricadas las rutas
* 2) Para establecer un timeout
* 3) que pasa con los CData y el envio de archivos
* 4) Hay que validar los casos genericos donde se envia informacion al servidor como datos de usuario contraseña y Json Token
*/
async function request(url, params, method = 'GET') {
//los parametros que le vamos a enviar al fetch
const options = {
method,
headers: {
'Content-Type': 'application/json' // we will be sending JSON
}
};
//solo para el get enviaremos los parametros por url, si es otro lo enviaremos por el body
if (params) {
if (method === 'GET') {
//url += '?' + objectToQueryString(params);
url += '/' + params;
} else {
options.body = JSON.stringify(params); // body should match Content-Type in headers option
}
}
//esperamos a que la promesa termine para poder ejecutarlo, fetch es una promesa
let result;
try {
const response = await fetch(BaseUrl + url, options);
if (response.status !== 200) {
result = generateErrorResponse('Ocurrió un error.', response.status);
}
result = await response.json(); // convertimos el resultado en json
}
catch (e) {
result = generateErrorResponse(e.message, 500);
}
return result;
}
function generateErrorResponse(message, status) {
return {
codigo: 'error',
message,
status
};
}
function get(url, params) {
return request(url, params);
}
function create(url, params) {
return request(url, params, 'POST');
}
function update(url, params) {
return request(url, params, 'PUT');
}
function remove(url, params) {
return request(url, params, 'DELETE');
}
//Convierte el objeto en parametros para la url (solo para el caso del get)
function objectToQueryString(obj) {
return Object.keys(obj).map(key => key + '=' + obj[key]).join('&');
}
export default {
get,
create,
update,
remove
};
Then i created another module which uses the router to fetch data from specific url and retrieve Json formated data from it, the module is this:
import RouterModule from './RouterModule.js'
import GetListOptions from './Helpers/HtmlHelpers.js'
const relativeUrl = "/personas"
export async function ObtenerSelectPersonasAsync(UsuarioId, htmlSelectObj) {
try {
const ResponseArray = await RouterModule.get(relativeUrl, UsuarioId !== 0 ? UsuarioId : null)
const ListOptions = GetListOptions(ResponseArray, 'personaId', 'nombre', '3', htmlSelectObj)
return ListOptions;
}
catch (e) {
return {
error: 'Error',
status: 404
}
}
}
export async function ObtenerPersonas(UsuarioId) {
try {
const ResponseArray = await RouterModule.get(relativeUrl, UsuarioId !== 0 ? UsuarioId : null)
return ResponseArray;
}
catch (e) {
return {
error: 'Error',
status: 404
}
}
}
export default {
ObtenerPersonas,
ObtenerSelectPersonasAsync
}
So the final programmer just needs to use the PersonasModule in order to work with database (this is in my mind, please correct me if i'm doing something wrong),
So in index.html they just need to this:
<script type="module">
import { ObtenerSelectPersonasAsync, ObtenerPersonas } from './JsModules/PersonasModule.js';
let Persona = ObtenerPersonas(1) //here it's supposed to retrieve an array however im getting a promise
Persona.then(result => {
inputNombre.value = result[0].nombre;
})
</script>
can you please tell me why is this happening, am i missing something? maybe i'm doing some nasty stuff and there is a better way to do this, if you can guide me in the right way i'll be grateful, thank you so much.