Skip to content

Instantly share code, notes, and snippets.

@farhad-taran
farhad-taran / README.md
Last active March 23, 2025 23:47
How to run a Javascript function at a specific time of day

some scenarios require us to run a piece of code at a specific time of day, the following method allows us to do this:

function runAtSpecificTimeOfDay(hour, minutes, func)
{
  const twentyFourHours = 86400000;
  const now = new Date();
  let eta_ms = new Date(now.getFullYear(), now.getMonth(), now.getDate(), hour, minutes, 0, 0).getTime() - now;
  if (eta_ms < 0)
 {
@farhad-taran
farhad-taran / README.md
Last active August 24, 2021 19:23
Comparing two json objects in automated tests

In some scenarios it is necessary to compare the structure of json documents in your automated tests. for example you might want to make sure that the json representation of what is in your storage, mirrors whats returned by to what is returned from your apis.

its also possible that these two different sources have some fields missing or that they serialize the data in different ways, for example a json string might represent numbers as single digit unless explicitly made to use decimals.

the following c# object allows for comparing two expando objects, the idea is to load a json string representation as an expando object using any json parser that you like, and be able to compare it to another. using expando objects makes this implementation agnostic to different json serializers.

using System;
using System.Collections;
using System.Collections.Generic;
@farhad-taran
farhad-taran / README.md
Last active September 13, 2021 16:37
RXJS, newrelic and recording failed or succeeded observables

recording events related to observables can be tricky and might cause a lot of duplication in code, the following snippet allows for handling such scenarios in a cleaner way:

import * as newrelic from 'newrelic';
import { Observable } from 'rxjs';
import { catchError, map } from 'rxjs/operators';

export function recordCustomEvent(
  isSuccess: boolean,
  eventName: string,
@farhad-taran
farhad-taran / README.md
Last active August 18, 2021 17:39
reusable key value pair mock for services such as config providers

sometimes we want to stub a service that returns a value for a key, for example a config provider. the following reusable construct uses jest which can reduce the number of duplicated boiler plate code.

export default (mockedMethodName: string, keyValueMap: Map<string, string>) => {
  const mock = {};
  mock[mockedMethodName] = (key: string) => {
    const value = keyValueMap.get(key);
    if (!value) {
      throw new Error(`${key} not present in ${mockedMethodName} in keyValueMock`);
@farhad-taran
farhad-taran / README.md
Last active August 7, 2021 20:53
Result and ErrorResponse pattern in typescript

Following is an implementation of the result monad, this monad can be used in place of throwing errors:

Result Type:

class Result<T>{
    private constructor(success: boolean, content: T, error: IErrorResponse | null) {
        this.success = success;
        this.error = error;
    }
 static success(content: T) {
@farhad-taran
farhad-taran / README.md
Created May 14, 2021 18:50
Creating the Lazy pattern construct in javascript

when fetching an expensive and costly object that might not be used frequently or not at all, its best to load and fetch it lazily, ie, only fetch it when the process requires it.

the below code is an implementation of the Lazy pattern which is already available in C#.

export default class Lazy {
  #value;
  #fetch;

  constructor(valueFetcher) {
@farhad-taran
farhad-taran / README.md
Last active May 7, 2021 14:11
AWS Lambda CLI commands for doing Canary deployments

I have written the following reusable scripts which can be used to aid with canary deployment of AWS Lambdas.

Get the latest version number of a lambda:

latest_version=$(aws lambda list-versions-by-function --function-name lambda-test \
  --no-paginate \
  --query "max_by(Versions, &to_number(to_number(Version) || '0'))" | jq -r ".Version")
  
echo "Latest version is: ${latest_version}"
@farhad-taran
farhad-taran / README.md
Last active May 6, 2021 23:01
Implementing lambda aliasing, versioning and traffic shifting for AWS Lambda using Terraform

In the below snippet I am creating an alas for my newly deployed lambda and setting a traffic weight for the previous version of this lambda if it exists, if a previous version of the lambda does not exist then all the traffic would be passed to the latest version.

resource "aws_lambda_alias" "main_alias" {
  count            = var.publish ? 1 : 0
  name             = "LATEST"
  description      = "LATEST lambda alias"
  function_name    = aws_lambda_function.main.function_name
  function_version = aws_lambda_function.main.version
  
  #sets traffic of the previous version if available to a portion out of 100% causing the new version to take the rest
@farhad-taran
farhad-taran / README.md
Created May 4, 2021 09:26
Masking properties in a JSON string

Some times we have a requirement to mask properties in a json string, these fields could be personal information that need to be hidden from prying eyes under the GDPR regulations. while json parse allows you to pass a function and selectively mask properties as they are being parsed, this becomes harder if you are already dealing with a JSON string and do not want to parse it to an object, mask it and parse it back to a string representation.

the following method uses two regex scripts to parse a normal json string and a json string that has had its quotes escaped.

export function maskProperty(jsonString, propId, mask) {
  const maskedEscapedJson = applyMask(jsonString,`\\\\"${propId}\\\\":\\\\"[^,]*`, `\\"${propId}\\":\\"${mask}\\"`);
  const maskedNormalJson = applyMask(jsonString, `"${propId}":[ \\t]*"[^,]*`, `"${propId}": "${mask}"`);
  return maskedEscapedJson.applied ? maskedEscapedJson.maskedJson : maskedNormalJson.maskedJson;
@farhad-taran
farhad-taran / README.md
Created April 26, 2021 13:54
Testing a single file in NPM

sometimes we only want to test a single file or debug it selectively and running the whole test suit can be very time consuming in these scenarios. the following script can be added to the package.json of an application and ease this process:

"test-file": "read -p 'input test file: ' name && npm test -- $name"

the above script will ask for the filename to be input and then it will pass it on to the appropriate test runner.