Skip to content

Completed some tasks. #6

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions JavaScript/rewritedServer/cache.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
'use strict';

const cache = {};

const setCache = (url, cacheData) => {
cache[url] = cacheData;
}

const getFromCache = (url) => {
return cache[url];
}

module.exports = {
setCache,
getFromCache
}
6 changes: 6 additions & 0 deletions JavaScript/rewritedServer/config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
'use strict';

module.exports = {
HOST_NAME: 'localhost',
PORT: 8000
}
53 changes: 53 additions & 0 deletions JavaScript/rewritedServer/controllers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
'use strict';

const { setCache } = require('./cache');
const { parseCookies } = require('./cookies');
const { personGetService, personPostService } = require('./services');

const defaultController = (req, res) => {
const cookies = parseCookies(req);
res.writeHead(200, {
'Set-Cookie': 'mycookie=test',
'Content-Type': 'text/html'
});
const ip = req.connection.remoteAddress;
res.write(`<h1>Welcome</h1>Your IP: ${ip}`);
res.end(`<pre>${JSON.stringify(cookies)}</pre>`);
}

const personGetController = async (req, res) => {
const result = await personGetService();
setCache(req.url, result);
if (result) {
res.writeHead(200);
res.end(result);
} else {
res.writeHead(500);
res.end('Read error');
}
}

const personPostController = (req, res) => {
const body = [];

req.on('data', (chunk) => {
body.push(chunk);
}).on('end', async () => {
let data = Buffer.concat(body).toString();
const obj = JSON.parse(data);
data = await personPostService(obj);
if (data) {
res.writeHead(200);
res.end('File saved');
} else {
res.writeHead(500);
res.end('Write error');
}
});
}

module.exports = {
defaultController,
personGetController,
personPostController
}
18 changes: 18 additions & 0 deletions JavaScript/rewritedServer/cookies.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
'use strict';

const { logger } = require('./loger');

const parseCookies = (req) => {
const cookie = req.headers.cookie;
logger.cookie(cookie);
const cookies = {};
if (cookie) cookie.split(';').forEach((item) => {
const parts = item.split('=');
cookies[(parts[0]).trim()] = (parts[1] || '').trim();
});
return cookies;
}

module.exports = {
parseCookies
}
34 changes: 34 additions & 0 deletions JavaScript/rewritedServer/loger.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
'use strict';

class Logger {
constructor(logColor = '\x1b[42m', errorColor = '\x1b[41m', cookieColor = '\x1b[45m') {
this.logColor = logColor;
this.errorColor = errorColor;
this.cookieColor = cookieColor;
}

setDefaultColor() {
console.log('\x1b[0m');
}

log(...messages) {
console.log(`${this.logColor}${new Date().toISOString()} : ${messages.join(' ')}`);
this.setDefaultColor();
}

error(...messages) {
console.log(`${this.errorColor}${new Date().toISOString()} : ${messages.join(' ')}`);
this.setDefaultColor();
}

cookie(cookie) {
console.log(`${this.cookieColor}${cookie}`);
this.setDefaultColor();
}
}

const logger = new Logger();

module.exports = {
logger
}
1 change: 1 addition & 0 deletions JavaScript/rewritedServer/person.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"name":"John","age":"23"}
13 changes: 13 additions & 0 deletions JavaScript/rewritedServer/routing.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
'use strict';

const { defaultController, personGetController, personPostController } = require('./controllers');

module.exports = {
GET: {
'/': defaultController,
'/person': personGetController
},
POST: {
'/person': personPostController
}
};
15 changes: 15 additions & 0 deletions JavaScript/rewritedServer/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
'use strict';

const http = require('node:http');
const { PORT } = require('./config');
const routing = require('./routing');
const { logger } = require('./loger');
const { getFromCache } = require('./cache');

http.createServer((req, res) => {
logger.log(req.method, req.url);
if (req.method === 'GET' && getFromCache(req.url)) {
return getFromCache(req.url);
}
routing[req.method][req.url](req, res);
}).listen(PORT);
35 changes: 35 additions & 0 deletions JavaScript/rewritedServer/services.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
'use strict';

const fs = require('node:fs').promises;

const personGetService = async () => {
try {
const data = await fs.readFile('./person.json');
const obj = JSON.parse(data);
obj.birth = new Date(obj.birth);
const difference = new Date() - obj.birth;
obj.age = Math.floor(difference / 31536000000);
delete obj.birth;
const sobj = JSON.stringify(obj);
return sobj;
} catch (e) {
return false;
}
}

const personPostService = async (obj) => {
try {
if (obj.name) obj.name = obj.name.trim();
const data = JSON.stringify(obj);
await fs.writeFile('./person.json', data);
return data;
} catch (e) {
console.error(e);
return false;
}
}

module.exports = {
personGetService,
personPostService
}