Skip to content

Providing Higher Order Functions for common getServerSideProps scenarios #7

@e1himself

Description

@e1himself

I had this idea with this package providing higher-order functions to provide extended context to the wrapped getServerSideProps function to simplify common scenarios.

An example using such approach with HTTP env headers and Prezly API client:

function withHttpEnv<Context extends GetServerSidePropsContext, Props>(
    getServerSideProps: (
        context: Context & { env: Env },
    ) => Props | Promise<Props>,
) {
    return function (context: Context) {
        const env = getEnvVariables(context.req);

        return getServerSideProps({ ...context, env });
    };
}
function withPrezlyApi<Context extends GetServerSidePropsContext, Props>(
    getServerSideProps: (
        context: Context & { api: PrezlyApi },
    ) => Props | Promise<Props>,
) {
    return withHttpEnv(function (context: Context) {
        const { PREZLY_ACCESS_TOKEN, PREZLY_NEWSROOM_UUID } = context.env;
        if (!PREZLY_ACCESS_TOKEN) {
           throw new Error('"PREZLY_ACCESS_TOKEN" is not set in env variables.');
        }
        if (!PREZLY_NEWSROOM_UUID) {
           throw new Error('"PREZLY_NEWSROOM_UUID" is not set in env variables.');
        }
    
        const api = new PrelzlyApi(PREZLY_ACCESS_TOKEN, PREZLY_NEWSROOM_UUID);
        
        return getServerSideProps({ ...context, api });
    });
}

and then the usage will be something like this:

export const getServerSideProps: GetServerSideProps<BasePageProps> = withPrezlyApi(async (context) => {
    const api = context.api; 
    const env = context.env;
    // use API and env
});

what do guys you think about this approach?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions