Skip to content

Instantly share code, notes, and snippets.

View lihaibh's full-sized avatar

Lihai Ben-Haim lihaibh

  • Israel
View GitHub Profile
@lihaibh
lihaibh / exponential-backoff-retry.util.ts
Last active February 24, 2023 13:39
An elegant way of performing exponential backoff retries on an async operation, using rxjs streams
import { Type } from '@nestjs/common';
import { defer, lastValueFrom, switchMapTo, throwError, timer } from 'rxjs';
import { catchError } from 'rxjs/operators';
export function withRetry<
T,
F extends (...args: any[]) => Promise<T>,
>(options: { retries: number; exceptErrors?: Type<Error>[]; fn: F }): F {
return (async (...args) => {
@lihaibh
lihaibh / rate-limit.util.ts
Last active February 24, 2023 13:39
Rate limit wrapper - wraps an async function, make sure the calls do not exceed the rate limit
export function withRateLimit<T, E extends (...args: any[]) => Promise<T>>({ fn, limit, every }: {
fn: E,
// maximum amount of executions in specific amount of time
limit: number,
// the amount in milliseconds we are limiting the total amount of executions
every: number
}): E {
let lastExecTime = -1;
let requestCounter = 0;
let triggerFlushTimeout = null;
@lihaibh
lihaibh / return-type.ts
Last active February 24, 2023 13:39
Get return type of a function
async function getItems() {
const requestTime = new Date();
const response = await fetch('http://myservice/items');
const items = (await response.json()) as { id: string; price: number }[];
const responseTime = new Date();
return {
items,
requestTime,
responseTime,
@lihaibh
lihaibh / cypress.config.ts
Last active October 11, 2022 10:34
Cypress: code coverage configuration
import { defineConfig } from 'cypress';
let codeCoverageEnv = {};
// make sure code coverage is enabled
if (process.env.CODE_COVERAGE_ENABLED === 'true') {
codeCoverageEnv = {
codeCoverage: {
url: `${
process.env.cypress_baseUrl || 'http://backend:9001'
@lihaibh
lihaibh / backup-disk.sh
Last active August 4, 2018 19:10
create snapshot of a remote linux disk to your local machine
#/usr/bin/env sh
SSH_HOST=host.name
BACKUP_DISK="sda"
DISK_SIZE_BYTES=`expr 1073741824 \* $(ssh $SSH_HOST "lsblk --all | grep \"$BACKUP_DISK\" | head -1" | while read c1; do echo $c1; done | cut -d" " -f4 | sed "s/G//g")`
BLOCK_SIZE=512
IMAGE_NAME="./sda.disk"
[ -f $IMAGE_NAME ] && IMAGE_CUR_SIZE=$(stat -c "%s" $IMAGE_NAME) || IMAGE_CUR_SIZE=0
WRITEN_BLOCKS=$(($IMAGE_CUR_SIZE / $BLOCK_SIZE))
echo -e "Current clone file size: \e[1m$IMAGE_CUR_SIZE\e[0m, total remote disk size: \e[1m$DISK_SIZE_BYTES\e[0m"
@lihaibh
lihaibh / MariaDB.repo
Created February 13, 2016 07:57
MariaDB.repo for CentOS7 (64 bit)
# MariaDB 10.1 CentOS repository list - created 2016-02-13 07:56 UTC
# http://mariadb.org/mariadb/repositories/
[mariadb]
name = MariaDB
baseurl = http://yum.mariadb.org/10.1/centos7-amd64
gpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB
gpgcheck=1