Launch Week Day 2: Introducing Reports: An Extensible Reporting Framework for Socket Data.Learn More
Socket
Book a DemoSign in
Socket

@profusion/lazy-load-obj

Package Overview
Dependencies
Maintainers
7
Versions
2
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@profusion/lazy-load-obj

Lazy Load Object Fields

latest
Source
npmnpm
Version
1.0.1
Version published
Maintainers
7
Created
Source

Lazy Load Object Fields

Simple Proxy that coordinates loading fields of an object on demand.

This is useful to be matched with GraphQL, where one can return a shallow object (ie: { id }) and let the properties be loaded in one go once used.

Example

See examples/.

/* eslint-disable no-console */
/* eslint-disable import/no-extraneous-dependencies */
import process from 'process';
import fetch from 'node-fetch';

import lazyLoadObj from '../lib';

const baseUrl = 'https://jsonplaceholder.typicode.com/';

type Todo = {
  completed: boolean;
  id: number;
  title: string;
};

const lazyTodo = lazyLoadObj<Todo>(
  { id: Number(process.argv[2] || 1) },
  async (
    { id }: Partial<Todo>,
    properties: readonly (keyof Todo)[],
  ): Promise<Partial<Todo>> => {
    console.log(`loading todos/${id} properties`, properties);
    const response = await fetch(`${baseUrl}todos/${id}`);
    return response.json();
  },
);

const { title } = lazyTodo;
console.log('accessing title results in', title);
if (title instanceof Promise) {
  console.log('wait title promise...');
  title.then(
    value => {
      console.log('fetched title', value);
      // the next access will always return a value, since it's cached:
      console.log('access cached title', lazyTodo.title);
    },
    error => console.error('failed to fetch title', error),
  );
}

FAQs

Package last updated on 05 May 2020

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts