UNPKG

@microbitsclub/microbits-client

Version:
109 lines (84 loc) 2.75 kB
# Microbits Typescript Client Wrapper around the Microbits HTTP API. ## Installation ``` npm install @microbitsclub/microbits-client ``` ## Configuration [Get your merchant ID and API key](https://microbits.club/a/signin?redirect=https%3A%2F%2Fmicrobits.club%2Fa%2Fdevelopers). ## Usage Create a `MicrobitsClient` instance. ```typescript const microbits = new MicrobitsClient({ merchantId: '<your_merchant_id>', apiKey: '<your_api_key>', }); ``` Create a `RequestHandlerConfig` object. ```typescript 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. ```typescript const clientRequestHandler = getClientRequestHandler<Ctx>(microbitsConfig); const paywallRequestHandler = getContentRequestHandler<Ctx>(microbitsConfig); ``` Forward GET requests to the client and paywall request handlers. ```typescript fastify.route({ method: 'GET', url: `${DEFAULTS.MERCHANT_ROUTE_PREFIX}/*`, async handler(request, reply) { const result = await microbitsClientRequestHandler({ request, reply }, request.url); reply.send(result); }, }); ``` ```typescript 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