Best practice for REST API


#1

Hey guys, what’s the best practice struturing and call services in REST API?

This is my code and I would like other opinions about the best way to make this.

Do you do it any other way?

obs: Sorry for my english, I’m learning :sweat_smile:

services.js

var Observable = require("FuseJS/Observable");

//Production
var ROOT_URL = "myurl";

function apiFetch(path, options) {
	var url = encodeURI(ROOT_URL + path);

	if(options === undefined) {
		options = {};
	}
	
	// If a body is provided, serialize it as JSON and set the Content-Type header
	if(options.body !== undefined) {
		options = Object.assign({}, options, {
			body: JSON.stringify(options.body),
			headers: Object.assign({}, options.headers, {
				"Content-Type": "application/json"
			})
		});
	}

	// Fetch the resource and parse the response as JSON
	return fetch(url, options)
	.then(function(response) {
		return response.json().then(function(data){
			return data;
		});
	});
}

module.exports = {
	apiFetch: apiFetch
}

login.js

var Observable = require("FuseJS/Observable");

// Variables
var email = Observable();
var password = Observable();

// Public functions
function login() {
	busy.activate();

    checkInputValue();

	var user= {
		"email": email.value,
		"password": password.value
	};

	loginUser(user).then(function(result) {
		if(!result.erro){
			console.dir(result.data);
		}else{

		}
		busy.deactivate();
	});
}

// End Public functions


// Private functions
function checkInputValue(){
	if(!email.value || !password.value){
		console.log("Email or password is invalid");
		busy.deactivate();
		return;
	}
}
// End Private functions


// Call REST API

var sharedService = require("../../../shared/services/services.js");

function loginUser(obj) {
	return sharedService.apiFetch("login", {
		method: "POST",
		body: obj
	});
};

// End Call REST API

module.exports = {
	email: email,
	password: password,
	login: login
};

#2

There’s no fixed way of doing it but I think you’ve got the right idea. I would keep my “requires” at the top of the page though.