Skip to content

Latest commit

 

History

History
78 lines (60 loc) · 2.56 KB

README.md

File metadata and controls

78 lines (60 loc) · 2.56 KB

ToFlowGeneratorFunction

codecov npm

The toFlowGeneratorFunction is a utility function that converts a promise-returning function into a generator-returning function. It is designed to enable the usage of type-safe yield statements inside MobX flow wrapper.

Parameters

  • fn: The promise-returning function to be converted into a generator-returning function.

Examples

import { flow } from 'mobx';
import { toFlowGeneratorFunction, type FlowGenerator } from 'to-flow-generator-function';

interface UserData {
    id: number;
    name: string;
    age: number;
}

const fetchUserName = (id: number): Promise<string> => Promise.resolve('John');
const fetchUserAge = (id: number): Promise<number> => Promise.resolve(25);

function* fetchUserData(id: number): FlowGenerator<UserData> {
    const name = yield* toFlowGeneratorFunction(fetchUserName)(id);
    // Here, `name` has the type `string`.
    const age = yield* toFlowGeneratorFunction(fetchUserAge)(id);
    // Here, `age` has the type `number`.
    return {
        id,
        name,
        age,
    };
}

const userId = 3;
const userData = await flow(fetchUserData)(userId);
// Here, `userData` has the type `UserData`.
type GithubProject = number;
declare function fetchGithubProjectsSomehow(): Promise<GithubProject[]>;
declare function somePreprocessing(projects: GithubProject[]): GithubProject[];

class Store {
    githubProjects: GithubProject[] = [];
    state = 'pending';

    fetchProjects = flow(function* (this: Store): FlowGenerator<GithubProject[]> {
        this.githubProjects = [];
        this.state = 'pending';
        try {
            // yield instead of await.
            const projects = yield* toFlowGeneratorFunction(fetchGithubProjectsSomehow)();
            const filteredProjects = somePreprocessing(projects);
            this.state = 'done';
            this.githubProjects = filteredProjects;
        } catch (error) {
            this.state = 'error';
        }
        return this.githubProjects;
    });
}

const store = new Store();
const projects: GithubProject[] = await store.fetchProjects();

More examples in toFlowGeneratorFunction.spec.ts

Alternative solutions

https://mobx-state-tree.js.org/API/#togeneratorfunction