0.3.0 • Published 2 years ago

@microbitsclub/microbits-client v0.3.0

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

Microbits Typescript Client

Wrapper around the Microbits HTTP API.

Installation

npm install @microbitsclub/microbits-client

Configuration

Get your merchant ID and API key.

Usage

Create a MicrobitsClient instance.

const microbits = new MicrobitsClient({
    merchantId: '<your_merchant_id>',
    apiKey: '<your_api_key>',
});

Create a RequestHandlerConfig object.

interface Ctx {
    request: FastifyRequest;
    reply: FastifyReply;
}

const microbitsConfig: RequestHandlerConfig<Ctx> = {
    microbits,
    getUserSessionIdCookie(ctx, name) {
        return ctx.request.cookies[name];
    },
    setUserSessionIdCookie(ctx, name, userSessionId) {
        ctx.reply.setCookie(name, userSessionId, {
            path: '/',
            maxAge: 60 * 60 * 24 * 7,
            secure: true,
            httpOnly: false,
        });
    },
};

getUserSessionIdCookie must return the value of the named cookie.

setUserSessionIdCookie must set the value of the named cookie to userSessionId. The cookie must not be HttpOnly in order for the client paywall to be able to access it.

Create configured request handlers.

const clientRequestHandler = getClientRequestHandler<Ctx>(microbitsConfig);
const paywallRequestHandler = getContentRequestHandler<Ctx>(microbitsConfig);

Forward GET requests to the client and paywall request handlers.

fastify.route({
    method: 'GET',
    url: `${DEFAULTS.MERCHANT_ROUTE_PREFIX}/*`,
    async handler(request, reply) {
        const result = await microbitsClientRequestHandler({ request, reply }, request.url);
        reply.send(result);
    },
});
fastify.route({
    method: 'GET',
    url: '/story/:storyId',
    async handler(request, reply) {
        const result = await microbitsPaywallRequestHandler({ request, reply }, request.url);

        if (result.type === 'error') {
            reply.status(result.error.statusCode);
            reply.send(result.error.message);
            return;
        }

        if (result.ok.type === 'serve-content') {
            const { storyId } = request.params as { storyId: string };

            const story = stories.find(x => x.id === storyId);

            if (story === undefined) {
                reply.status(404);
            } else {
                reply.status(200);
                reply.send(story);
            }
        } else {
            reply.status(204);
            reply.send(result.ok.contentUrl);
        }
    },
});

Here we assume that there is a single group URL paywall for the path /story.

TODO hard paywall