0.0.1 • Published 9 months ago

ts-resource-utils v0.0.1

Weekly downloads
-
License
ISC
Repository
-
Last release
9 months ago

ts-resource-utils

Reusable Helper classes for your web dev projects

Event Handling and Resource Utilities

A set of utility classes designed to streamline event handling and resource management in TypeScript projects. These utilities enable efficient event observation and provide a clean way to manage asynchronous resources while maintaining a clear status-aware approach.

Features

  • Events Handling: The Events<T> class offers a mechanism to manage and observe events with content of type T. It allows you to handle events once and keep track of their status.

  • EventObserver: The EventObserver<T> class provides a convenient way to observe events of type Events<Resource<T>> and respond to different status states, such as success and error.

  • Resource Management: The Resource<T> class simplifies the management of asynchronous resources. It encapsulates data and error messages, and provides static methods for creating successful or error states.

  • Status Enumeration: The Status enum enhances clarity by defining status states such as Success and Error.

  • Safe Call Utility: The safeCall<T> function assists in making asynchronous calls safer by handling exceptions and encapsulating them into Resource error states.

Installation

npm install event-resource-utils

Usage

Simple Fetch call

import { safeCall } from "ts-resource-utils/utils/Safecall";
import { Resource } from "./Resource";

export class DefaultMainRepository implements MainRepository {
  async getUsers(): Promise<Resource<User>> {
    return safeCall<User>(async () => {
      const fetchResponse = await fetch(
        "https://jsonplaceholder.typicode.com/todos/1"
      );
      const response = await fetchResponse.json();
      const user: User = response;
      return Resource.Success(user);
    }) as Promise<Resource<User>>;
  }
}

Get user in viemodel

import { Events } from "ts-resource-utils/utils/Events";
import { container } from "di";
import { MainRepository } from "repoInterface";

const repository = container.resolve < MainRepository > "MainRepository";

const getUser = async () => {
  const result = await repository.getUsers();
  return new Events(result);
};

export { getUser };

Observing response

import { EventObserver } from "ts-resource-utils/utils/Events";
import { getUser } from "./HomeViewModel";
import { useState } from "react";

const subscribeToObserve = async () => {
  const [user, setUser] = useState<User>();

  const result = await getUser();
  new EventObserver(
    (error) => {
      console.log(error);
    },
    (data: User) => {
      setUser(data);
    }
  ).onChange(result);
};
0.0.1

9 months ago

0.1.0

9 months ago

1.0.0

9 months ago