Skip to content

Instantly share code, notes, and snippets.

@dmorosinotto
dmorosinotto / using_bcrypt.js
Created August 27, 2023 15:58
Using BCrypt to hash password in Node.js
//READ MORE IN THIS ARTICLE https://morioh.com/a/782c0022755e/using-bcrypt-to-hash-passwords-in-nodejs EXPECIALLY PRE-REQUISITE
const bcrypt = require("bcrypt")
const saltRounds = 10
const password = "Admin@123"
//Password encryption + explicit Salt
bcrypt
.genSalt(saltRounds)
.then(salt => {
@dmorosinotto
dmorosinotto / Chau_computeFrom.ts
Last active August 21, 2023 06:29
computedFrom - Useful function to combine Signal, Observable, Promise -> toSignal + optional pipe operators chain //INSPIRED BY @Enea_Jahollari ARTICLE https://dev.to/this-is-angular/a-sweet-spot-between-signals-and-observables-4chb
//ORIGINAL CODE BY CHAU: https://gist.github.com/eneajaho/33a30bcf217c28b89c95517c07b94266
import { isSignal, Signal, untracked } from '@angular/core';
import { toObservable, toSignal } from '@angular/core/rxjs-interop';
import {
combineLatest,
distinctUntilChanged,
from,
isObservable,
ObservableInput,
of,
@dmorosinotto
dmorosinotto / trackby.directive.ts
Last active September 16, 2023 17:25
TrackById, TrackByProp directives to simplify use of trackBy in Angular *ngFor
//INSPIRED BY https://medium.com/ngconf/make-trackby-easy-to-use-a3dd5f1f733b
import { Directive, inject, Provider } from "@angular/core";
import { ngForOf, NgIterable } from "@angular/common";
@Directive({
selector: "[ngForTrackById]",
standalone: true
})
export class NgForTrackByIdDirective<T extends { id: string | number }> {
@dmorosinotto
dmorosinotto / create-effect.ts
Last active July 31, 2023 13:28 — forked from e-oz/create-effect.ts
Helper function to handle async call and push value to Signal
//Helper function to handle async call (Observable generator with strategy + safe retry if error) to push value to Signal - useful for State Management with Signal
//READ MORE https://medium.com/@eugeniyoz/application-state-management-with-angular-signals-b9c8b3a3afd7
//ORIGINAL DOCS (NgRx component-store effect) https://ngrx.io/guide/component-store/effect#effect-method
import { isObservable, Observable, of, retry, Subject, Subscription } from 'rxjs';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { DestroyRef, inject } from '@angular/core';
/**
* This code is a copied `ComponentStore.effect()` method from NgRx and edited to:
* 1) be a standalone function;
@dmorosinotto
dmorosinotto / suspensify.ts
Created July 21, 2023 16:16
suspensify() - RxJS operator to convert maybeFailingObs$<T> => Obs$ that never fails and emit "state" { pending, finalized, hasValue + value: T, hasError + error:any }
//ORIGINAL CODE https://github.com/jscutlery/devkit/tree/main/packages/operators
import {
MonoTypeOperatorFunction,
Observable,
ObservableNotification,
OperatorFunction,
ReplaySubject,
} from 'rxjs';
import { debounce, map, materialize, scan, startWith } from 'rxjs/operators';
@dmorosinotto
dmorosinotto / has-role.directive.ts
Last active July 27, 2023 09:41
*hasRole="ROLE" Angular structural directive
import { Directive, EmbeddedViewRef, Input, TemplateRef, ViewContainerRef } from "@angular/core";
import { AuthService } from "./auth.service";
import { Subscription, Subject } from "rxjs";
@Directive({
selector: "[hasRole]",
standalone: true
})
export class HasRoleDirective {
constructor(
@dmorosinotto
dmorosinotto / safeCall.ts
Last active March 8, 2023 15:20
safeCall function (like RUST) + generic SafeResult<T> with TypeScript
//ORIGINAL CODE BY https://twitter.com/mattpocockuk/status/1633064377518628866?s=20
/**
* First, create a type helper that represents
* the result that we'll get from our safe function
*/
export type SafeResult<T> =
| {
ok: true;
value: T;
@dmorosinotto
dmorosinotto / fromReadable.ts
Created February 13, 2023 09:30
RxJS - fromReadableStream operator to trasform Readable Stream -> Observable
//ORIGINAL CODE INSPIRED BY Wassim Chegham https://twitter.com/manekinekko/status/1624440889216057347/photo/1
export function fromReadableStream(
stream: ReadableStream,
signal?: AbortSignal,
writableStrategy?: QueuingStrategy,
readableStrategy?: QueuingStrategy
): Observable<string> {
const createTextDecoderStream = ()=> new TextDecoderStream();
const transformer = () => new TransformStream(
{ transform(chunk, controller) { controller.enqueue(chunk); } }
@dmorosinotto
dmorosinotto / typescript.json
Last active January 26, 2023 10:26
Snippet for @input @output as Observable for Angular (VSCode Cmd+P > Snippets: Configure User Snippets)
"@Input Observable for Angular": {
"prefix": "in$",
"description": "Create an Observable @Input",
"body": [
"#${1:prop} = new BehaviorSubject<${2:type}|undefined>(undefined);",
"protected ${1:prop}\\$ = this.#${1:prop}.pipe(filter(p=>p!==undefined));",
"@Input() set ${1:prop}(value: ${2:type}) {",
"\t$0//if (value!==this.${1:prop}) //eventual validation logic",
"\tthis.#${1:prop}.next(value);",
"}",
@dmorosinotto
dmorosinotto / BaseFormCtrl.ts
Last active November 25, 2022 17:41
Base custom FormControl (NG_VALUE_ACCESSOR implementation) compatible with [(two-way)] + [(ngModel)] + ReactiveForms / ngx-formly ^_^
import { ChangeDetectionStrategy, Directive, EventEmitter, Input, OnDestroy, Output } from "@angular/core";
import { ControlValueAccessor, NG_VALUE_ACCESSOR } from "@angular/forms";
import { Subject } from "rxjs";
@Directive(/*{
selector: "base-formctrl",
standalone: true,
// templateUrl: "./n-date-picker.component.html", //IL TEMPLATE VA SPECIFICATO SULLA @Component OSSIA LA CLASSE EREDITATA
// styleUrls: ["./n-date-picker.component.css"], //GLI STYLE VANNO SPECIFICATI SULLA @Component OSSIA LA CLASSE EREDITATA
// providers: [{ provide: NG_VALUE_ACCESSOR, useExisting: NBaseFormCtrlComponent, multi: true }], //PURTROPPO QUESTO NON FUNZIONA SULLA ABSTRACT DEVO FARE IL PROVIDER NELLA CLASSE EREDITARE