Skip to content

Instantly share code, notes, and snippets.

View olehcambel's full-sized avatar
🐍

Олег Моисеенко olehcambel

🐍
  • @[object Object]
  • Kyiv
View GitHub Profile
@olehcambel
olehcambel / async-parallel.js
Created November 6, 2018 18:03
Promise.all with catch
module.exports = async (items, callback) => {
const errors = [];
const promises = [];
try {
if (!items && !Array.isArray(items))
throw `type 'items ${items}' should be Array`;
items.forEach(item => {
promises.push(callback(item).catch(err => errors.push(err)));
@olehcambel
olehcambel / fetch
Created November 28, 2018 08:09
promise \ callback => async \ await
const fetch = () => {
return new Promise((resolve, reject) => {
this.validate('name')
.then(result => {
return resolve(result.id)
})
.catch(reject)
})
}
@olehcambel
olehcambel / controller1.js
Last active January 3, 2019 16:03
How to handle async errors?
const app = require('express')();
const getConvert = async (req, res, next) => {
try {
throw 'err';
} catch (err) {
next(err)
}
};
@olehcambel
olehcambel / db.js
Last active January 12, 2019 20:22
const mysql = require('mysql')
const pool = mysql.createConnection({
host: config.db.host,
user: config.db.user,
password: config.db.password,
database: config.db.database,
});
class DB {
@olehcambel
olehcambel / app.js
Created February 28, 2019 21:07 — forked from joshnuss/app.js
Express.js role-based permissions middleware
// the main app file
import express from "express";
import loadDb from "./loadDb"; // dummy middleware to load db (sets request.db)
import authenticate from "./authentication"; // middleware for doing authentication
import permit from "./permission"; // middleware for checking if user's role is permitted to make request
const app = express(),
api = express.Router();
// first middleware will setup db connection
@olehcambel
olehcambel / onsuccess.helper.ts
Created March 13, 2019 11:59
generic + overload
interface OnSuccessResponse<T> {
statusCode: number
message: string
data: T
error: null
}
export function onSuccess<T>(): OnSuccessResponse<T>
export function onSuccess<T>(params: { message?: string, data?: T | null }): OnSuccessResponse<T>
export function onSuccess<T>(params: {message?: string, data?: T | null}={}) {
@olehcambel
olehcambel / app.ts
Created March 30, 2019 13:04
async error handling with express
import { asyncWrap } from './async-wrap';
const app = express();
asyncWrap();
@olehcambel
olehcambel / tokens.md
Created September 23, 2019 07:07 — forked from zmts/tokens.md
Про токены, JSON Web Tokens (JWT), аутентификацию и авторизацию. Token-Based Authentication

Про токены, JSON Web Tokens (JWT), аутентификацию и авторизацию. Token-Based Authentication

Основы:

Аутентификация(authentication, от греч. αὐθεντικός [authentikos] – реальный, подлинный; от αὐθέντης [authentes] – автор) - это процесс проверки учётных данных пользователя (логин/пароль). Проверка подлинности пользователя путём сравнения введённого им логина/пароля с данными сохранёнными в базе данных.

Авторизация(authorization — разрешение, уполномочивание) - это проверка прав пользователя на доступ к определенным ресурсам.

Например после аутентификации юзер sasha получает право обращатся и получать от ресурса "super.com/vip" некие данные. Во время обращения юзера sasha к ресурсу vip система авторизации проверит имеет ли право юзер обращатся к этому ресурсу (проще говоря переходить по неким разрешенным ссылкам)

@olehcambel
olehcambel / hello-node.js
Created March 22, 2020 19:18 — forked from nf/hello-node.js
Hello world web server that scales across multiple processors
var cluster = require('cluster');
var http = require('http');
var numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
// Fork workers.
for (var i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', function(worker, code, signal) {
@olehcambel
olehcambel / copy.go
Created March 25, 2020 20:24
go copy impl
func copy(dst, src []T) int {
for i := range dst {
src[i] = dst[i]
}
return cap(dst) - cap(src)
}
t := make([]byte, len(s), (cap(s)+1)*2)
copy(t, s)