Skip to content

Instantly share code, notes, and snippets.

@benixal
Last active February 4, 2023 20:27
Show Gist options
  • Save benixal/29490f8d4ca918a953c2157825c6318b to your computer and use it in GitHub Desktop.
Save benixal/29490f8d4ca918a953c2157825c6318b to your computer and use it in GitHub Desktop.
a simple API server with GET , POST , PUT , PATCH , DELETE methods
const http = require('http');
var fs = require('fs');
const port = 8060;
var db = "database";
if (!fs.existsSync(db)) {
fs.mkdirSync(db);
}
http.createServer((req, res) => {
const headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': '*',
'Access-Control-Request-Method': '*',
'Access-Control-Allow-Headers': '*',
};
if (req.method === 'OPTIONS') {
res.writeHead(204, headers);
res.end();
return;
}
var splitedurl = req.url.split("/");
splitedurl = splitedurl.filter(function (e) { return e });
var dir = "";
var param = "";
if (splitedurl.length > 0) {
var splitedcleanurl = splitedurl.join("/").split("?");
dir = db + "/" + splitedcleanurl[0];
param = splitedcleanurl[1];
}
if (dir.includes('favicon.ico') || dir == "") {
res.writeHead(200, { ...headers, "content-type": "text/html" });
res.end(
'<!DOCTYPE html>' +
'<html lang="en">' +
'<head>' +
' <meta charset="UTF-8">' +
' <meta http-equiv="X-UA-Compatible" content="IE=edge">' +
' <meta name="viewport" content="width=device-width, initial-scale=1.0">' +
' <title>simple API test server</title>' +
'<style> body {font-family: system-ui;background-color:black;color:white} p {letter-spacing: .2rem;} p>span { color:#009688 ; } </style>'+
'</head>' +
'<body>' +
"<p> <h1>Welcome to simple API test </h1> " +
"database folder is : <strong>" + __dirname + "/database</strong> <br>" +
"<p style='line-height:4rem;font-size:1.5rem'>available methods : [GET , POST , PUT , PATCH , DELETE] <br>" +
"<strong>GET</strong> : http://127.0.0.1:" + port + "/<span>FOLDER_NAME</span><br>" +
"<strong>POST</strong> : http://127.0.0.1:" + port + "/<span>FOLDER_NAME</span> and JSON data<br>" +
"<strong>PUT</strong> : http://127.0.0.1:" + port + "/<span>FOLDER_NAME</span>/<span>RECORD_ID</span> and JSON data<br>" +
"<strong>PATCH</strong> : http://127.0.0.1:" + port + "/<span>FOLDER_NAME</span>/<span>RECORD_ID</span> and JSON data<br>" +
"<strong>DELETE</strong> : http://127.0.0.1:" + port + "/<span>FOLDER_NAME</span>/<span>RECORD_ID</span></p>" +
'</body>' +
'</html>');
return;
}
res.writeHead(200, { ...headers, "content-type": "application/json" });
if (req.method === 'GET' || req.method === 'POST') {
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
}
if (req.method === 'GET') {
var perpage = 10;
process.argv.slice(2).forEach((val, index, array) => {
if (val.includes("paginate")) {
perpage = val.split("paginate=")[1];
}
})
var page = null;
if (param !== undefined && param != "") {
page = param.split("page=")[1];
}
if (page === undefined || page == "" || page == null || page == 0) {
page = 1;
}
var ret = [];
var count = 0;
fs.readdir(dir, (err, files) => {
files.forEach(file => {
count++;
if (count > page * perpage - perpage && count <= page * perpage) {
ret.push(JSON.parse(fs.readFileSync(dir + "/" + file, 'utf8')));
}
});
res.end(JSON.stringify(ret));
});
}
var body = "";
req.on("data", function (chunk) {
body += chunk;
});
if (req.method === 'POST') {
req.on("end", function () {
var id = 1;
while (fs.existsSync(dir + "/" + id)) {
id++;
}
var filedata = JSON.parse(body);
filedata['id'] = id;
fs.writeFile(dir + "/" + id, JSON.stringify(filedata), function (err, file) {
if (err) throw err;
res.end(JSON.stringify({ id: id, message: "added" }));
})
});
}
if (req.method === 'PUT') {
req.on("end", function () {
var id = dir;
var putdata = JSON.parse(body);
fs.writeFile(id, JSON.stringify(putdata), function (err, file) {
if (err) throw err;
res.end(JSON.stringify({ message: "updated" }));
})
});
}
if (req.method === 'PATCH') {
req.on("end", function () {
var id = dir;
var filedata;
var patchdata;
fs.readFile(id, 'utf8', function (err, data) {
if (err) throw err;
filedata = JSON.parse(data);
patchdata = JSON.parse(body);
Object.keys(patchdata).forEach(function (key) {
try {
filedata[key] = patchdata[key];
} catch (error) {
console.log(error)
}
});
fs.writeFile(id, JSON.stringify(filedata), function (err, file) {
if (err) throw err;
res.end(JSON.stringify({ message: "patched" }));
})
});
});
}
if (req.method == 'DELETE') {
var filename = dir;
fs.unlink(filename, function (err) {
if (err) return console.log(err);
res.end(JSON.stringify({ message: "deleted" }));
});
}
}).listen(port);
console.log("simple API test is ready on http://127.0.0.1:" + port);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment