Jean-Yves Didier

added rest component

import ARCS from '../engine/arcs.js';
let RestWrapper;
/**
* @class RestWrapper
* @classdesc A wrapper for REST requests
*
*/
RestWrapper = ARCS.Component.create(
function() {
const request = async function(method, url, obj) {
const requestOptions = {
method: method,
headers: {'Content-Type': 'application/json'},
};
if (obj) requestOptions.body = JSON.stringify(obj);
let response = await fetch(url, requestOptions);
if (! response.ok) return null;
let data = await response.json();
if (data === null)
return response.status;
return data;
};
/**
* Read REST request (GET)
* This idea is to obtain a resource through a specific URL.
* The resource is then sent through the <b>send</b> signal.
* @slot
* @emits send
* @param {string} url
*/
this.read = async function(url) {
let output = await request('GET', url);
this.emit('send', output);
};
/**
* Create REST request (PUT)
* The passed object is created through the PUT request
* @slot
* @param {string} url
* @param {Object} obj
*/
this.create = async function(url, obj) {
let output = await request('PUT', url, obj);
};
/**
* Update REST request (POST)
* The passed object is updated through the POST request
* @slot
* @param {string} url
* @param {Object} obj
*/
this.update = async function(url, obj) {
let output = await request('POST', url, obj);
};
/**
* Delete REST request (DELETE)
* The resource is destroyed through the request
* @param {string} url
*/
this.delete = async function(url) {
let output = await request('DELETE',url);
};
},
['create','read','update','delete'],
['send']
/*
Reminder of REST API:
- GET: read
- PUT: create
- POST: update
- DELETE: delete
*/
);
export default {RestWrapper};
\ No newline at end of file