Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/profusion/lazy-load-obj
TypeScript utility to lazy load object properties when they are accessed
https://github.com/profusion/lazy-load-obj
Last synced: about 1 month ago
JSON representation
TypeScript utility to lazy load object properties when they are accessed
- Host: GitHub
- URL: https://github.com/profusion/lazy-load-obj
- Owner: profusion
- Created: 2020-03-05T19:40:41.000Z (almost 5 years ago)
- Default Branch: master
- Last Pushed: 2023-01-07T15:36:59.000Z (almost 2 years ago)
- Last Synced: 2024-11-07T01:02:58.424Z (about 2 months ago)
- Language: TypeScript
- Size: 1.5 MB
- Stars: 0
- Watchers: 22
- Forks: 0
- Open Issues: 15
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Lazy Load Object Fields
Simple [Proxy](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/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/](./examples/).
```typescript
/* 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(
{ id: Number(process.argv[2] || 1) },
async (
{ id }: Partial,
properties: readonly (keyof Todo)[],
): Promise> => {
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),
);
}
```