@angular-package/callback

Manages the callback function.

Usage no npm install needed!

<script type="module">
  import angularPackageCallback from 'https://cdn.skypack.dev/@angular-package/callback';
</script>

README

Packages

Useful and simple to use packages based on the angular.io.

Package Description Status
callback Manages the callback function. npm version
change-detection Improves application performance. npm version
component-loader Handles dynamic loading components. npm version
core Core features. npm version
error Manages an Error. npm version
prism Prism highlighter module. npm version
property Handles object properties. npm version
reactive Automatize the process of creating some rxjs features. npm version
testing Support for testing other packages. npm version
type Common types, type guards, and type checkers. npm version
ui User interface. In Progress

Click on the package name to visit its GitHub page.

angular-package/callback

Manages the callback function.

npm version

GitHub issues GitHub forks GitHub stars GitHub license

GitHub sponsors Support me on Patreon


Table of contents



Basic concepts

Checks

It's to check the provided value to be the same as expected.

Type guard (constrain)

Constrains the parameter type to not let input unexpected value in the code editor.

Guards

It's a combination of both above, constrains the type of the parameter in the code editor, and checks its provided argument.

Defines

Returns defined value from a method of an object.
Defines new value in an object and returns a defined value.

Gets

Returns a value from an object.

Sets

Adds or updates an element with a specified key and a value to an object and returns an object.


Skeleton

This package was built by the library skeleton which was generated with Angular CLI version 12.1.1.

Copy this package to the packages/callback folder of the library skeleton then run the commands below.

Build

Run ng build callback to build the package. The build artifacts will be stored in the dist/ directory.

Running unit tests

Run ng test callback to execute the unit tests via Karma.


Installation

Install @angular-package/callback package with command:

npm i @angular-package/callback --save

Api

import {
  // Class.
  Callback,

  // Type.
  CallbackPayload
} from '@angular-package/callback';

Callback

Manages the callback function of a ResultCallback type.


Static methods:

Callback. Description
defineResultCallback() Defines the function of ResultCallback type that contains a ResultHandler function to handle the result and optional payload
defineErrorCallback() Defines the function of ResultCallback type to throw ValidationError with a specified message on a state from the throwOnState
guard() Guards the provided resultCallback to be ResultCallback type
isCallback() Checks if the provided value is an instance of Callback with optional indicating allowed names under which callback functions can be stored

Constructor:

Constructor Description
Callback() Initialize an instance of a Callback with the allowed names under which callback functions can be stored

Instance methods:

Callback.prototype. Description
getCallback() Gets from the storage specified by-name callback function of a ResultCallback type
setErrorCallback() Sets a callback function of a ResultCallback type that throws ValidationError with a specified message on a state from the provided throwOnState to the storage under the given allowed name restricted by AllowNames
setResultCallback() Sets a callback of a ResultCallback type to the storage under the given allowed name, which is restricted by AllowNames

Callback static methods


Callback.defineResultCallback()

Defines the function of a ResultCallback type that contains a ResultHandler function to handle the result and optional payload.

static defineResultCallback<Payload extends object>(
  resultHandler: ResultHandler<Payload>,
  capturePayload?: Payload
): ResultCallback<Payload> {
  return (result: boolean, payload?: Payload) => {
    if (is.function(resultHandler)) {
      resultHandler(result, payload);
    }
    return result;
  };
}

Generic type variables:

Name Description
Payload extends object The shape of the optional payload parameter of the ResultCallback and ResultHandler function, which is constrained by the object type. Its value can be captured from a type of the provided capturePayload optional parameter

Parameters:

Name: type Description
resultHandler: ResultHandler<Payload> The function that is guarded by the ResultHandler type to handle the result and optional payload of the ResultCallback function
capturePayload?: Payload An optional object of generic type Payload that is used only to capture the value by the generic type variable Payload

Returns:

Returns Type Description
ResultCallback<Payload> Function The return type is a function of ResultCallback

The return value is a function of a ResultCallback type that contains a function of ResultHandler.

Usage:

// Example usage.
import { Callback } from '@angular-package/callback';
import { is } from '@angular-package/type';

const stringCallback = Callback.defineResultCallback(
  (result: boolean, payload) => {
    if (is.false(result)) {
      console.log(`Something went wrong`, payload);
    }
  }
);

// Returns in console 'Something went wrong' 5
is.string(5, stringCallback);
// Another usage example.
import { Callback, ResultCallback } from '@angular-package/callback';

type Person = { id?: number; firstName?: string; age?: number };

const isPerson = (value: Person, callback: ResultCallback<Person>): any =>
  callback(typeof value === 'object', value);

const personCallback = Callback.defineResultCallback(
  (result: boolean, payload) => {
    if (payload !== undefined) {
      console.log(payload);
    }
    return result;
  }
);

// Console returns { firstName: 'My name' }
isPerson({ firstName: 'My name' }, personCallback);

Callback.defineErrorCallback()

Defines function of ResultCallback type to throw ValidationError with a specified message on a state from throwOnState. Provided payload from defined callback function of ResultCallback is being passed to a thrown error of ValidationError.

static defineErrorCallback<Payload extends object>(
  message: string | ErrorMessage,
  throwOnState: boolean = false,
  capturePayload?: Payload
): ResultCallback<Payload> {
  return Callback.defineResultCallback<Payload>(
    (result: boolean, payload?: Payload): void => {
      if (is.false(throwOnState) ? is.false(result) : is.true(result)) {
        throw Object.assign(new ValidationError(message), { payload });
      }
    }
  );
}

Generic type variables:

Name Description
Payload extends object The shape of the optional payload parameter of the ResultCallback function, which is constrained by the object type. Its value can be captured from a type of the provided capturePayload optional parameter

Parameters:

Name: type Description
message: string \| ErrorMessage The message of string type or ErrorMessage interface to throw with an error of ValidationError
throwOnState: boolean A state of boolean type on which an error of ValidationError should be thrown. By default, it's set to false
capturePayload?: Payload An optional object of generic type Payload that is used only to capture the value by the generic type variable Payload

Returns:

Returns Type Description
ResultCallback<Payload> Function The return type is a function of a ResultCallback type

The return value is a function of a ResultCallback type that throws a ValidationError.

Usage:

// Example usage.
import { Callback } from '@angular-package/callback';
import { is } from '@angular-package/type';

const stringCallback = Callback.defineErrorCallback('Something went wrong');
is.string(5, stringCallback); // Throws ValidationError: Something went wrong
import { Callback, ResultCallback } from '@angular-package/callback';

type Person = { id?: number; firstName?: string; age?: number };

const isPerson = (value: Person, callback: ResultCallback<Person>): any =>
  callback(typeof value === 'object', value);

const personCallback = Callback.defineErrorCallback('It is not a person', true);

try {
  isPerson({ id: 1, firstName: 'name', age: 27 }, personCallback);
} catch (e) {
  // Console returns {id: 1, firstName: "name", age: 27}
  console.log(e.payload);
}

Callback.guard()

Guards the provided resultCallback to be ResultCallback type.

static guard<Payload extends object>(
  resultCallback: ResultCallback<Payload>
): resultCallback is ResultCallback<Payload> {
  return guard.function(resultCallback);
}

Generic type variables:

Name Description
Payload extends object The shape of the optional payload parameter of the ResultCallback function, which is constrained by the object type

Parameters:

Name: type Description
resultCallback: ResultCallback<Payload> The function of ResultCallback type with the shape of payload from the generic type variable Payload to guard

Returns:

Returns Type Description
resultCallback is ResultCallback<Payload> boolean The return type is boolean as the result of its statement that indicates the provided resultCallback is a function of a ResultCallback type with the shape of payload from the generic type variable Payload

The return value is a boolean indicating whether the provided resultCallback parameter is a function.

Usage:

// Example usage.
import { Callback } from '@angular-package/callback';

Callback.guard(result => result); // Returns `true`.
Callback.guard({} as any); // Returns `false`.

Callback.isCallback()

Checks if the provided value is an instance of Callback with optional indicating allowed names under which callback functions can be stored.

static isCallback<AllowNames extends string>(
  value: any,
  ...allowNames: AllowNames[]
): value is Callback<AllowNames> {
  return is.instance(value, Callback);
}

Generic type variables:

Name Description
AllowNames extends string An optional generic type variable of AllowNames name that is constrained by the string type and is used to indicate allowed names under which callback functions can be stored for the return type value is Callback<AllowNames>. Its value can be captured from the provided allowNames rest parameter

Parameters:

Name: type Description
value: any The value of any type to check
...allowNames: AllowNames[] A rest parameter of AllowNames that is used only to capture the value by the generic type variable AllowNames to indicate allowed names for the Callback<AllowNames> return type

Returns:

Returns Type Description
value is Callback<AllowNames> boolean The return type is boolean as the result of its statement that indicates the provided value is a Callback with allowed names from the provided allowNames parameter or generic type variable AllowNames

The return value is a boolean indicating whether the value is an instance of Callback .

Usage:

// Example usage.
import { Callback } from '@angular-package/callback';

Callback.isCallback({}); // Returns `false`
Callback.isCallback(new Callback()); // Returns `true`

const callback = new Callback('one', 'two', 'three');
if (Callback.isCallback(callback)) {
  callback.setCallback('one', result => result); // There's no hint on `name` parameter about allowed names.
}
if (Callback.isCallback(callback, 'one', 'two')) {
  callback.setCallback('one', result => result); // There is a hint from the provided `allowNames` parameter of the `isCallback()` method.
}

Callback constructor


Callback()

Initialize an instance of a Callback with the allowed names under which callback functions can be stored.

new Callback<AllowNames extends string>(...allowNames: AllowNames[]) {
  this.#allowedNames = guard.array(allowNames)
    ? new Set(allowNames)
    : this.#allowedNames;
}

Generic type variables:

Name Description
AllowedNames extends string A generic type variable AllowNames that is constrained by the string type and is used to restrict allowed names under which callback functions can be stored. By default, its value is captured from the provided allowNames rest parameter

Parameters:

Name: type Description
allowNames: AllowedNames[] A rest parameter of a string type allowed names under which callback functions can be stored. Only those names given by this parameter are being checked by the isNameAllowed() private method

Returns:

The return value is new instance of a Callback.

Usage:

// Example usage.
import { Callback } from '@angular-package/callback';
/**
 * Initialize `Callback`.
 */
const callback = new Callback('set', 'define');

Callback instance methods


Callback.prototype.getCallback()

Gets from the storage specified by-name callback function of a ResultCallback type.

public getCallback<
  Payload extends object,
  Name extends AllowNames = AllowNames
>(
  name: Name,
  capturePayload?: Payload
): Pick<CallbackStorage<Payload>, Name>[Name] {
  return this.#storage.get(name);
}

Generic type variables:

Name Description
Payload extends object The shape of the optional payload parameter of the ResultCallback function, which is constrained by the object type. Its value can be captured from a type of the provided capturePayload optional parameter
Name extends AllowNames A generic type variable Name constrained by the AllowNames indicates the name under which callback function is picked from the storage. It is linked with the return type Pick<CallbackStorage, Name>[Name] that refers exactly to the type, which is ResultCallback of the callback function picked from the storage by Name. By default, its value is captured from the provided name

Parameters:

Name: type Description
name: Name A string type name that is restricted by the AllowNames to pick stored callback function
capturePayload?: Payload An optional object of generic type Payload that is used only to capture the value by the generic type variable Payload

Returns:

Returns Type Description
Pick<CallbackStorage, Name>[Name] function The return type is a ResultCallback function that is picked from the CallbackStorage by using Name

The return value is the callback function of a ResultCallback type picked from the storage.

Usage:

// Example usage.
import { Callback } from '@angular-package/callback';
/**
 * Initialize `Callback`.
 */
const callback = new Callback('firstName');

callback
  .setCallback('firstName', result => result) // Set the callback function under the given name.
  .getCallback('firstName'); // Get the function stored under the given name.
// Generic type variable payload example usage.
import { Callback } from '@angular-package/callback';
/**
 * Initialize `Callback`.
 */
const callbackInstance = new Callback('firstName');

// Type for the `Payload`.
type CustomPayload = { id: number, name: string };

// Set the callback function under the given name.
callbackInstance.setResultCallback<CustomPayload>('firstName', (result, payload) => {
  if (payload) {
    // It handles two properties from the payload.
    // payload.id
    // payload.name
  }
});

// Get the function stored under the given name with the `CustomPayload` type.
const firstNameCallback = callbackInstance.getCallback<CustomPayload>('firstName');

// Use the defined callback function with a defined `CustomPayload`.
firstNameCallback(false, { id: 5, name: 'there is no name', age: 1 }); // TypeError because of the `age`
// Captured payload example usage.
import { Callback } from '@angular-package/callback';
/**
 * Initialize `Callback`.
 */
const callbackInstance = new Callback('firstName');

// Constant from which is going to be captured type for the `Payload`.
const payLoadToCapture = { id: 1, name: '' };

// Set the callback function under the given name.
callbackInstance.setResultCallback(
  'firstName',
  (result, payload) => {
    if (payload) {
      // It handles two properties from the payload.
      // payload.id
      // payload.name
    }
  },
  payLoadToCapture
);

// Get the function stored under the given name.
const firstNameCallback = callbackInstance.getCallback(
  'firstName',
  payLoadToCapture
);

// Use the defined callback with a captured type of payload.
firstNameCallback(false, { id: 5, name: 'there is no name' });

Callback.prototype.setErrorCallback

Sets a function of a ResultCallback type to the storage under the given allowed name with the given error message to throw on the specified state from the throwOnState.

public setErrorCallback<Name extends AllowNames>(
  name: Name,
  message: string | ErrorMessage,
  throwOnState: boolean = false
): this {
  this.setCallback(name, Callback.defineErrorCallback(message, throwOnState));
  return this;
}

Generic type variables:

Name Description
Name extends AllowNames A generic Name variable constrained by the AllowNames indicates the name under which callback function is stored. By default, its value is captured from the provided name

Parameters:

Name: type Description
name: Name A string type name that is restricted by the AllowNames under which the function is stored. The allowed status of the provided name is checked by the private method isNameAllowed()
message: string \| ErrorMessage The message of string type or ErrorMessage interface, to throw with an error of ValidationError
throwOnState: boolean A state of boolean type on which an error of ValidationError should be thrown. By default, it's set to false

Returns:

Returns Type Description
this object The return type is an instance of Callback

The return value is an instance of Callback.

Usage:

// Example usage.
import { Callback } from '@angular-package/callback';
/**
 * Initialize `Callback`.
 */
const callback = new Callback('firstName', 'lastName');

// Set the error callback function under the given name.
callback.setErrorCallback('lastName', 'LastName must be a string type', false);

Callback.prototype.setResultCallback()

Sets a callback function of a ResultCallback type to the storage under the given allowed name restricted by AllowNames.

public setResultCallback<
  Payload extends object,
  Name extends AllowNames = AllowNames
>(
  name: Name,
  resultHandler: ResultHandler<Payload>,
  capturePayload?: Payload
): this {
  if (this.isNameAllowed(name)) {
    this.#storage.set(
      name,
      Callback.defineResultCallback<Payload>(resultHandler)
    );
  }
  return this;
}

Generic type variables:

Name Description
Payload extends object The shape of the optional payload parameter of the ResultCallback function, which is constrained by the object type. Its value can be captured from a type of the provided capturePayload optional parameter
Name extends AllowNames A generic type variable Name constrained by the AllowNames indicates the name under which callback function is stored. By default, its value is captured from the provided name

Parameters:

Name: type Description
name: Name A string type name that is restricted by the AllowNames under which the function is stored. The allowed status of the provided name is checked by the private method isNameAllowed()
resultHandler: ResultHandler The function of ResultHandler to handle the result of the ResultCallback function before its result returns

Returns:

Returns Type Description
this object The return type is an instance of Callback

The return value is an instance of Callback.

Usage:

// Example usage.
import { Callback } from '@angular-package/callback';
/**
 * Initialize `Callback`.
 */
const callback = new Callback('firstName');

// Set the callback function under the given name.
callback.setCallback('firstName', result => result) 
// Generic type variable `Payload` example usage.
import { Callback } from '@angular-package/callback';
/**
 * Initialize `Callback`.
 */
const callbackInstance = new Callback('firstName');

// Type for the `Payload`.
type CustomPayload = { id: number; name: string };

// Set the callback function under the given name.
callbackInstance.setResultCallback<CustomPayload>(
  'firstName',
  (result, payload) => {
    if (payload) {
      // It handles two properties from the payload.
      // payload.id
      // payload.name
    }
  }
);
// Captured `Payload` example usage.
import { Callback } from '@angular-package/callback';
/**
 * Initialize `Callback`.
 */
const callbackInstance = new Callback('firstName');

// Constant from which is going to be captured type for the `Payload`.
const payLoadToCapture = { id: 1, name: '' };

// Set the callback function under the given name.
callbackInstance.setResultCallback(
  'firstName',
  (result, payload) => {
    if (payload) {
      // It handles two properties from the payload.
      // payload.id
      // payload.name
    }
  },
  payLoadToCapture
);

Full usage example:

// Generic type variable `Payload` example usage.
import { Callback } from '@angular-package/callback';
/**
 * Initialize `Callback`.
 */
const callbackInstance = new Callback('firstName');

// Type for the `Payload`.
type CustomPayload = { id: number, name: string };

// Set the callback function under the given name.
callbackInstance.setResultCallback<CustomPayload>('firstName', (result, payload) => {
  if (payload) {
    // It handles two properties from the payload.
    // payload.id
    // payload.name
  }
});

// Get the function stored under the given name with the `CustomPayload` type.
const firstNameCallback = callbackInstance.getCallback<CustomPayload>('firstName');

// Use the defined callback function with a defined `CustomPayload`.
firstNameCallback(false, { id: 5, name: 'there is no name', age: 1 }); // TypeError because of the `age`
// Captured `Payload` example usage.
import { Callback } from '@angular-package/callback';
/**
 * Initialize `Callback`.
 */
const callbackInstance = new Callback('firstName');

// Constant from which is going to be captured type for the `Payload`.
const payLoadToCapture = { id: 1, name: '' };

// Set the callback function under the given name.
callbackInstance.setResultCallback(
  'firstName',
  (result, payload) => {
    if (payload) {
      // It handles two properties from the payload.
      // payload.id
      // payload.name
    }
  },
  payLoadToCapture
);

// Get the function stored under the given name.
const firstNameCallback = callbackInstance.getCallback(
  'firstName',
  payLoadToCapture
);

// Use the defined callback with a captured type of `Payload`.
firstNameCallback(false, { id: 5, name: 'there is no name' });

Interface

CallbackPayload

experimental

Experimental shape for a generic type variable Payload.

export interface CallbackPayload {
  action?: string;
  name?: string;
  param?: string;
  value?: any;
  [index: string]: any;
}

Properties:

action?: string
An optional action that describes the cause of performed callback.

name?: string
An optional name of the function or method that performed callback.

param?: string
An optional name of the parameter of a string type to which performed callback relates.

value?: any
An optional value of of related parameter of any type.

Usage:

// Example usage.
import { CallbackPayload, ResultCallback } from '@angular-package/callback';

// Create a new function.
const isString = (
  value: any,

  // Parameter callback of `ResultCallback` type with the `CallbackPayload`.
  callback: ResultCallback<CallbackPayload>
): any => {
  callback(typeof value === 'string', {
    // Property from the `CallbackPayload`.
    action: 'Checks the string of a firstName',

    // Property from the `CallbackPayload`.
    name: 'isString',

    // Property from the `CallbackPayload`.
    param: 'value',

    // Property from the `CallbackPayload`.
    value,

    // Custom property.
    firstName: 'my Name',
  });
};

// The use of the `isString()` function.
isString('it is a string', (result: boolean, payload) => {
  if (payload !== undefined) {
    /*
    Returns {
      action: "Checks the string of a firstName",
      firstName: "my Name",
      name: "isString",
      param: "value",
      value: "it is a string",
    }
    */
    console.log(payload);
  }
  return result;
});

Type

ResultCallback

Represents a callback function with parameters, a result of a boolean type, and an optional payload of a generic type Payload.

type ResultCallback<Payload extends object = any> = (
  result: boolean,
  payload?: Payload
) => boolean;

Generic type variables:

Payload extends object
The shape of the optional payload parameter that is constrained by the object type.

Parameters:

result: boolean
Result of a boolean type that is returned. What the result concerns is not specified, so it can be anything - the creator decides.

payload?: Payload
An optional object of a generic type Payload to provide more data.

Returns: The return value is a boolean indicating state of the result of any action.


ResultHandler

Function to handle the result and optional payload of the ResultCallback function before its result returns.

type ResultHandler<Payload extends object = any> = (
  result: boolean,
  payload?: Payload
) => void;

GIT

Commit

Versioning

Semantic Versioning 2.0.0

Given a version number MAJOR.MINOR.PATCH, increment the:

  • MAJOR version when you make incompatible API changes,
  • MINOR version when you add functionality in a backwards-compatible manner, and
  • PATCH version when you make backwards-compatible bug fixes.

Additional labels for pre-release and build metadata are available as extensions to the MAJOR.MINOR.PATCH format.

FAQ How should I deal with revisions in the 0.y.z initial development phase?

The simplest thing to do is start your initial development release at 0.1.0 and then increment the minor version for each subsequent release.

How do I know when to release 1.0.0?

If your software is being used in production, it should probably already be 1.0.0. If you have a stable API on which users have come to depend, you should be 1.0.0. If you’re worrying a lot about backwards compatibility, you should probably already be 1.0.0.

License

MIT © angular-package (license)