Skip to content

Instantly share code, notes, and snippets.

@Pan-Maciek
Created February 20, 2017 12:00
Show Gist options
  • Select an option

  • Save Pan-Maciek/5b887bef13a6b47a96b924e4b38dac68 to your computer and use it in GitHub Desktop.

Select an option

Save Pan-Maciek/5b887bef13a6b47a96b924e4b38dac68 to your computer and use it in GitHub Desktop.
var fs = require("fs"); // const
var qs = require("querystring"); // const
console.log("Start API"); // unikaj console.logów w API tego będą używac ludzie i na tej zadzadnie tworzyć interfejsy ty im niczego nie narzucaj tylko ważne informacje typu błędy mogą być wyświetlane
// proponował bym żeby moduł zwracał funkcje tworzącą serwer albo odrazu utworzony serwer coś jak express
module.exports = function (req, res) {
return {
res: res, // mozna zapisac wtedy tylko res
req: req, // req: req ==== req nie trzeba tyle pisać
ViewLang: function (static, page) { // mozna zapisac poprostu ViewLang(static, page)
var data = fs.readdir(static, function (err, files) { // może fat arrow ? (err, files) => {}
if (err) {
console.log("error"); // ale precyzja jak kurwa jakiś ninja throw err lub console.log(err) no już ostatecznie console.log('[ViewLang error]', err); żęby dodać możliowość filtrowania logów
}
else {
var alang = req.headers["accept-language"]
for (var i = 0; i < files.length; i++) {
if (alang.indexOf(files[i]) > -1) { // to nie jest dobry pomysł w sensie ta pętla
console.log(static + "/" + files[i] + "/" + page); // jaką to ma dawać informacje ?
fs.readFile(static + "/" + files[i] + "/" + page, function (error, data) { // mozna to zapisać jako `${static}/${files[i]/${page}`
if (error) {
res.write("Error");
res.end(); // wystarczyło by res.end("Error") no ale
}
else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(data);
res.end(); // też wystarczy res.end(data);
return; // nie potrzebny return wewnątrz callbacku
}
})
}
}
}
})
},
GetFile: function (dir, url) { // GetFile (dir, url)
if (url.indexOf(".") > -1) { // a co jak ktoś ma plik index.min.html albo coś w ten deseń? powinneś tu uzyc regex i co jak ktoś napisze index.
var roz = url.substring(url.indexOf(".") + 1, url.length); // ?
var name = url.substring(1, url.indexOf(".")); // ?
name = trans.Change(name, function (string) {
});
fs.readFile(dir + "/" + roz + "/" + name + "." + roz, function (error, data) {
if (error) {
res.writeHead(404);
res.write("not found")
res.end();
}
else {
res.writeHead(200, { 'Content-Type': 'text/' + roz })
res.write(data);
res.end();
}
})
}
},
View: function (file) { // niezgodność z dokumentacją https://www.npmjs.com/package/easynodeapi#apiview---odesłanie-pliku-html
fs.readFile(file, function (error, data) {
if (error) {
res.write("Error " + error);// , error inaczje zamienisz error do uproszczonej wersji
res.end();
}
else {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(data);
res.end();
}
})
},
File: function (file) {
var roz = file.substring(file.indexOf(".", 1) + 1, file.length);
fs.readFile(file, function (error, data) {
if (error) {
res.write("Error " + error);
console.log(error);
res.end();
}
else {
if (roz == "css") {
res.writeHead(200, { 'Content-Type': 'text/css' });
}
else {
res.writeHead(200, { 'Content-Type': 'text/plain' });
}
res.write(data);
res.end();
}
})
},
Json: function (data) { // bez sensu
res.writeHead(200, { 'Content-Type': "application/json" })
res.write(JSON.stringify(data));
res.end();
},
Table: function (data) { // ???
res.writeHead(200, { 'Content-Type': "text/plain" })
var resdata = "[" + JSON.stringify(data) + " ]";
res.write(resdata);
res.end();
},
SendPOSTData: function (func) {
var str = "";
var obj = {};
var dat = new Date();
req.on("data", function (data) {
str += data;
})
req.on("end", function (data) {
obj = qs.parse(str);
if (func) {
func(obj);
}
res.end(JSON.stringify(obj));
})
},
GetPOSTData: function (func) {
var str = "";
var obj = {};
var dat = new Date();
req.on("data", function (data) {
str += data;
})
req.on("end", function (data) {
obj = qs.parse(str);
if (func) {
func(obj)
}
})
},
SavePOSTData: function (name, func) { // że co?
var str = "";
var obj = {};
var dat = new Date();
req.on("data", function (data) {
str += data;
})
req.on("end", function (data) {
obj = qs.parse(str);
if (func) {
func(obj)
}
this.Data = AddToObject(this.Data, name, obj);
})
},
GetData: function (name) {
return eval("this.Data." + name); // zabić ? optymalizacja przez interpreter właśnie poszła się jebać
//return this.Data[name] -_-
},
OnGETUrl: function (url, func) { // nie komentuje tych on..
var reqUrl = UrlFilter(url);
this.ServerFunc.push({ url: reqUrl, method: "GET", func: func });
/*if (reqUrl == url && req.method == "GET")
{
func();
this.executedReq = true;
}*/
},
OnPOSTUrl: function (url, func) {
var reqUrl = UrlFilter(url);
this.ServerFunc.push({ url: reqUrl, method: "POST", func: func });
/*if (reqUrl == url && req.method == "POST")
{
func();
this.executedReq = true;
}*/
},
OnUrl: function (method, url, func) {
var reqUrl = UrlFilter(url);
this.ServerFunc.push({ url: reqUrl, method: method, func: func });
/*if(reqUrl == url && req.method == method)
{
func();
this.executedReq = true;
}*/
},
Default: function (func) { // ooookej
this.ServerDefault = func;
/*if (func && !this.executedReq)
{
func();
}*/
},
Data: { // ? no a wiesz ze każdy może to zmodyfikować ? a skoro tak to po co dawac default value ?
Author: "Mateusz Stabryła"
},
Tab: { // co ma robić tab ? dlaczego to nie jest z innymi funckcjami globalnymi ?
RemFromArray: function (index, table) {
if (index = table.length) {
table.pop()
return table;
}
else {
for (var i = index; i < table.length - 1; i++) {
table[index] = table[index + 1];
}
table.pop();
return table;
}
}
},
executedReq: false, // wait co to ???
ServerDefault: null, // tak porprostu srv default ?
ServerFunc: [],
Server: function () { // że przepraszam co robi ta funckcja ?
if (!this.ServerDefault) {
console.log("You must set the default response"); // pomocne w pizdu ja bym zrobił jeszcze coś odnośnie 404
}
for (var i = 0; i < this.ServerFunc.length; i++) {
if (this.req.url == this.ServerFunc[i].url && this.req.method == this.ServerFunc[i].method) {
this.ServerFunc[i].func();
this.executedReq = true;
return;
}
}
if (!this.executedReq) {
this.ServerDefault();
}
}
}
}
function AddToObject(obj, name, value) { // do usunięcia
eval("obj." + name + " = " + JSON.stringify(value)); // wow wow wow w8 co kurwa ! :O
return obj;
// wypierdol tą funkcje całą i rób tak obj[name] = value i nie grzesz nigdy więcej XD
}
function UrlFilter(url) {
var ret = "";
for (var i = 0; i < url.length; i++) {
if (url[i] == "?") {
return ret;
}
else {
ret += url[i];
}
}
return url;
// return const UrlFilter = url => url.match(/.*?(?=\?)/)[0] // no prosz :v wszystko do ? w 1 lini
}
/*
1 - nie przestrzeganie konwencji nazwenictwa json
2 - zbrodnia dla optymalności aplikacji - eval dobrze tylko raz uzyte
3 - zamiast jednego on('metoda' ...) to najebane ile bądź OnGETUrl OnPOSTUrl OnUrl
jak dla mnie:
użytecznosć 5/10 nie dokońca rozumie dlaczego mam tworzyć normalnie serwer i wewnątrz odpalać jakby to api
wyknanie 4/10 - za ten eval to z -2000 sie należy XD
stosowanie es6 0/100000000...000 :P
dokumentacja 4/10 - dlaczego tak połowa po polsku polowa po ang no 1 języka sie tzymaj
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment