Skip to content

Instantly share code, notes, and snippets.

@raslan1994
Created December 12, 2020 15:56
Show Gist options
  • Select an option

  • Save raslan1994/af48b97a2fc8b2e07ce95dd8cca524e8 to your computer and use it in GitHub Desktop.

Select an option

Save raslan1994/af48b97a2fc8b2e07ce95dd8cca524e8 to your computer and use it in GitHub Desktop.
Simple & Elegant REST full api structure (js)
API_URL=http://localhost:8080
/**
* The MIT License (MIT)
Copyright (c) 2019 Raslan Rauff
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import { writeLog, LogLevel } from './appLogger'
const Config = {
baseUrl: process.env.API_URL,
apiUrl: (path) => Config.baseUrl + path,
}
const Endpoints = {
getProducts: () =>
Config.apiUrl('/api/products/'),
getProducts: (id) =>
Config.apiUrl('/api/products/' + id),
}
async function apiRequest(
url,
method = 'GET',
body = null,
defaultValue = null
) {
writeLog(LogTag, '[started][' + method + '] =>' + url, LogLevel.debug)
let response = defaultValue
try {
const options =
method == 'PUT' || method === 'POST'
? {
method,
body: JSON.stringify(body),
}
: {
method,
}
const apiResponse = await fetch(url, {
...options,
//TODO enable following when testing with Mocknoon
// mode: 'cors',
})
response = await apiResponse.json()
writeLog(
LogTag,
'[end][' + method + '] => ' + url,
LogLevel.debug,
LogLevel.debug
)
writeLog(LogTag, response, LogLevel.debug)
} catch (ex) {
writeLog(LogTag, '[error][' + method + '] => ' + url, LogLevel.warn)
writeLog(LogTag, ex, LogLevel.error)
}
return response
}
export { Config, Endpoints, apiRequest }
import { Endpoints, apiRequest } from './api.js'
const apiResponse = await apiRequest(
Endpoints.getProducts("someProductId"),
'GET',
null,
{
id: 0,
name: "",
unitPrice: 0
})
//access response payload
console.log(apiResponse);
/**
* The MIT License (MIT)
Copyright (c) 2019 Raslan Rauff
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
const LogLevel = {
debug: 'd',
info: 'i',
warn: 'w',
error: 'error',
}
const isProductionStage = process.env.PRODUCTION
const writeLog = (tag, msg, type = LogLevel.debug) => {
if (type === LogLevel.debug && isProductionStage) return
const _tag = '[' + tag + ']'
switch (type) {
case LogLevel.debug:
console.log(_tag, msg)
return
case LogLevel.info:
console.info(_tag, msg)
return
case LogLevel.warn:
console.warn(_tag, msg)
return
case LogLevel.error:
console.error(_tag, msg)
return
}
}
export { LogLevel, writeLog }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment