Skip to content

Instantly share code, notes, and snippets.

@kharandziuk
kharandziuk / explanation.md
Last active April 27, 2017 12:26
Unnecessary promise wrapping explanation

Consider you are developing a math library which has a function isPi.

function isPi(x) {
  return x === 3.14
}

Now you are saying something like - We don't want to care where do we take the data(db, network, etc). So, we will receive a promise

var pg = require('pg');
var client = new pg.Client();
// connect to our database
client.connect(function (err) {
if (err) throw err;
// execute a query on our database
client.query('SELECT COUNT(*) FROM Hotels;', function (err, result) {
PG_USER=booking PG_PASSWORD=booking psql -h localhost -p 15432 booking -c 'SELECT COUNT(*) FROM Hotels;'
const H = require('highland')
const Promise = require('bluebird')
const _ = require('lodash')
const Writable = require('stream').Writable;
const SIZE = 10
function grabFromApi(i) {
console.log('start reading', i)
return Promise.delay(1000).then(() => {

Tip 1

check the .pendingMocks() after each test and don't share mocks between tests

describe('channel', function() {
    beforeEach(function() {
        nock.cleanAll()
    })
@kharandziuk
kharandziuk / article.md
Last active March 31, 2017 14:36
Node.js Streams и реактивное программирование

В этой статье мы попробуем решить реальную проблему при помощи Node.js Stream и чуточку Reactive Programming. В последнем не уверен – RP, в какой-то мере, "жупел"(как перевести buzzword?) о котором все говорят, но никто не "делает". Статья рассматривает практический пример и ориентирована на знакомого с платформой читателя, по-этому намеренно не объясняет базовые понятия – если что-то непонятно по Stream API, то стоит обратится в документацию платформы или в какой-нибудь ее пересказ(например, этот).

Начнем с описания проблемы: нам нужно построить “паучка” который заберет все данные с “чужого” REST API, как-то их обработает и запишет в “нашу” базу данных. Для удобства воспроизведения и моделирования мы опустим некоторые детали о конкретном API и базе данных(в реальности это было API одного известного стартапа связанного с гостиницами и Postgres база данных). Представим что у нас есть две функции(код функций как и весь код

@kharandziuk
kharandziuk / article.md
Last active March 2, 2021 03:41
Node.js Streams and Reactive Programming Primer

This article shows how to apply Node.js Stream and a bit of Reactive programming to a real(tm) problem. The article is intended to be highly practical and oriented for an intermediate reader. I intentionally omit some basic explanations. If you miss something try to check the API documentation or its retelling(e.g.: this one)

So, lets start from the problem description. We need to implement a simple web scraper which grabs all the data from some REST API, process the data somehow and inserts into our Database. For simplicity, I omit the details about the actual database and REST API(in real life it was the API of some travel fare aggregator website and a Pg database)

Consider we have two functions(code of the IO simulator functions and the other article code is here):

getAPI(n, count) // pseudo API ca
const scramjet = require("scramjet");
const {getAPI, insertDB} = require('./io-simulators')
const ROWS = 1000
// build a stream of indexes
new scramjet.DataStream({
read() {
this.offset = (this.offset || 0);
this.push(this.offset);
@kharandziuk
kharandziuk / async-vs-promise.js
Last active April 11, 2017 15:04
async-vs-promise
const Promise = require('bluebird')
function gogogo(queryList) {
return Promise
.resolve(queryList)
.map(getType)
.map(function(type) { // can be incapsulated in a function but original sample doesn't do that
if (type === 1) {
return getJson(query)
}
const Promise = require('bluebird')
function gogogo(queryList) {
const parts = []
for (const query of queryList) {
const type = await getType(query)
if (type === 1) {
parts.push(getJson(query))
}