Monday, October 31, 2022

Jest testing framework for React & Node.js

https://jestjs.io/docs/getting-started

{
"name": "project",
"version": "1.0.0",
"description": "API",
"main": "src/server.js",
"scripts": {
"test": "jest",
"test-watch": "jest --watchAll",
"start": "node src/server.js",
"watch": "nodemon src/server.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"cors": "^2.8.5",
"csv-parse": "^5.3.1",
"express": "^4.18.2",
"morgan": "^1.10.0"
},
"devDependencies": {
"jest": "^29.2.2",
"supertest": "^6.3.1"
}
}

npm i jest --save-dev

npm i supertest --save-dev

Portable anonymous Linux for privacy & security

GNOME Disks (gnome-disk-utility) equivalent in KDE: Startup Disk Creator (usb-creator-kde)

https://tails.boum.org/install/linux/index.en.html


Sunday, October 30, 2022

Run client & server in separate folders

Node.js server and React client:

"scripts": {
"install-server": "cd server && npm install",
"install-client": "cd client && npm install",
"install": "npm run install-server && npm run install-client",
"server": "cd server && npm run watch",
"client": "cd client && npm start",
"watch": "npm run server & npm run client",
"test": "echo \"Error: no test specified\" && exit 1"
},

Node.js server and React client:

"scripts": {
"install-server": "npm install --prefix server",
"install-client": "npm install --prefix client",
"install": "npm run install-server && npm run install-client",
"server": "npm run watch --prefix server",
"client": "npm start --prefix client",
"watch": "npm run server & npm run client",
"deploy": "npm run build --prefix client && npm start --prefix server",
"test": "npm test --prefix server & npm test --prefix client"
},

//

Thursday, October 27, 2022

http Node.js module status codes

node > http

STATUS_CODES: {
   '100': 'Continue',
   '101': 'Switching Protocols',
   '102': 'Processing',
   '103': 'Early Hints',
   '200': 'OK',
   '201': 'Created',
   '202': 'Accepted',
   '203': 'Non-Authoritative Information',
   '204': 'No Content',
   '205': 'Reset Content',
   '206': 'Partial Content',
   '207': 'Multi-Status',
   '208': 'Already Reported',
   '226': 'IM Used',
   '300': 'Multiple Choices',
   '301': 'Moved Permanently',
   '302': 'Found',
   '303': 'See Other',
   '304': 'Not Modified',
   '305': 'Use Proxy',
   '307': 'Temporary Redirect',
   '308': 'Permanent Redirect',
   '400': 'Bad Request',
   '401': 'Unauthorized',
   '402': 'Payment Required',
   '403': 'Forbidden',
   '404': 'Not Found',
   '405': 'Method Not Allowed',
   '406': 'Not Acceptable',
   '407': 'Proxy Authentication Required',
   '408': 'Request Timeout',
   '409': 'Conflict',
   '410': 'Gone',
   '411': 'Length Required',
   '412': 'Precondition Failed',
   '413': 'Payload Too Large',
   '414': 'URI Too Long',
   '415': 'Unsupported Media Type',
   '416': 'Range Not Satisfiable',
   '417': 'Expectation Failed',
   '418': "I'm a Teapot",
   '421': 'Misdirected Request',
   '422': 'Unprocessable Entity',
   '423': 'Locked',
   '424': 'Failed Dependency',
   '425': 'Too Early',
   '426': 'Upgrade Required',
   '428': 'Precondition Required',
   '429': 'Too Many Requests',
   '431': 'Request Header Fields Too Large',
   '451': 'Unavailable For Legal Reasons',
   '500': 'Internal Server Error',
   '501': 'Not Implemented',
   '502': 'Bad Gateway',
   '503': 'Service Unavailable',
   '504': 'Gateway Timeout',
   '505': 'HTTP Version Not Supported',
   '506': 'Variant Also Negotiates',
   '507': 'Insufficient Storage',
   '508': 'Loop Detected',
   '509': 'Bandwidth Limit Exceeded',
   '510': 'Not Extended',
   '511': 'Network Authentication Required'
 },

https://nodejs.org/api/http.html

Tuesday, October 25, 2022

Using local JSON file without database in Node.js

 //

////////////////////////////////////////////////////////
// JSON WITHOUT DATABASE
// //////////////////////////////////////////////////////
const fs = require('fs');
////////////////////////////////////////////////////////
const cards = JSON.parse(fs.readFileSync(`${__dirname}/data/card-data.json`));
////////////////////////////////////////////////////////
exports.checkId = (req, res, next, val) => {
if (req.params.id * 1 > cards.length) {
return res.status(404).json({
status: 'fail',
message: 'Invalid ID',
});
}
next();
};
////////////////////////////////////////////////////////
exports.getAllCards = (req, res) => {
res.status(200).json({
status: 'success',
time: req.requestTime,
result: cards.length, // if sending array!!!
data: { images: cards },
});
};
////////////////////////////////////////////////////////
exports.getCard = (req, res) => {
const id = req.params.id * 1; // convert String into Number
const card = cards.find((el) => el.id === id); // console.log(req.params);
res.status(200).json({
status: 'success',
time: req.requestTime,
data: {
card: card, // or just card instead of card: card
},
});
};
////////////////////////////////////////////////////////
exports.postCard = (req, res) => {
// solution to work without database
const newId = cards[cards.length - 1].id + 1;
const newCard = Object.assign({ id: newId }, req.body); // console.log(req.body);
cards.push(newCard);
fs.writeFile(
`${__dirname}/../data/card-data.json`,
JSON.stringify(cards),
(err) => {
res.status(201).json({
status: 'success',
data: { images: newCard },
});
}
); // use asynchronous writeFile
};
////////////////////////////////////////////////////////

//

Monday, October 24, 2022

Request logger for Node.js server

@desc    Logs request to console

const logger = (req, res, next) => {
console.log(
`${req.method} ${req.protocol}://${req.get('host')}${req.originalUrl}`
);
next();
};

module.exports = logger;

Morgan - HTTP request logger middleware for node.js

https://www.npmjs.com/package/express-requests-logger

https://github.com/expressjs/morgan

npm i morgan

TypeError('Router.use() requires a middleware function

throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn))

Check module.exports = ...

Sunday, October 23, 2022

Get unique values from array and remove duplicates

Extract unique values from arr1:

let arr1 = [1, 0, 1, 1, 2, 0, 2, 0, 2, 2];
    console.log( arr1.filter((el, i, a) => a.indexOf(el) === i) );
(3) [1, 0, 2]

 https://stackoverflow.com/questions/66527958/only-add-item-to-array-if-unique-otherwise-delete-react

https://stackoverflow.com/questions/11246758/how-to-get-unique-values-in-an-array

https://stackoverflow.com/questions/1960473/get-all-unique-values-in-a-javascript-array-remove-duplicates

https://stackoverflow.com/questions/15125920/how-to-get-distinct-values-from-an-array-of-objects-in-javascript

Create unique keys for React elements

- function to generate unique keys/ids/numbers/strings and use that

- existing npm packages like uuid, uniqid, etc

- generate random number `key-${new Date().getTime()}` with prefix from item being iterated

- using the unique ID from the database

https://stackoverflow.com/questions/39549424/how-to-create-unique-keys-for-react-elements