Example Counter Service

This is some example code for the service we just tested. It is written in typescript and uses express.


import express from "express";
import { expressjwt, Request as JWTRequest } from "express-jwt";
import jwksRsa from "jwks-rsa";

export class CounterModel {
  private _count: number;

  constructor() {
    this._count = 0;
  }

  get count() {
    return this._count;
  }

  increment() {
    this._count++;
  }

  decrement() {
    this._count--;
  }

  add(value: number) {
    this._count += value;
  }
}

const delegatedTokenAuth = expressjwt({
  secret: jwksRsa.expressJwtSecret({
    cache: true,
    rateLimit: true,
    jwksRequestsPerMinute: 5,
    jwksUri: "https://admin.m2worlds.io/.well-known/jwks.json",
  }) as any,
  audience: "scarcely-calm-lark",
  issuer: "scarcely-calm-lark:auth",
  algorithms: ["RS256"],
});


const app = express();

type CounterResponse = {
  counter: number;
};

type CounterUpdateRequest = {
  value: number;
};

// basic in memory counter
const counter = new CounterModel();

const userCounters = new Map<string, CounterModel>();

function findOrAddCounter(sub: string): CounterModel {
  let c = userCounters.get(sub);
  if (c) {
    return c;
  }

  c = new CounterModel();
  userCounters.set(sub, c);

  return c;
}

app.use(express.json());

app.head("/", (req, res) => {
  res.sendStatus(200);
});

app.get("/", (req, res) => {
  res.sendStatus(200);
});

// unauthenticated route
app.get<Record<string, never>, CounterResponse>("/api/counter", (req, res) => {
  res.send({ counter: counter.count });
});

// unauthenticated route
app.post<Record<string, never>, CounterResponse>("/api/counter", (req, res) => {
  counter.increment();
  res.send({ counter: counter.count });
});

// unauthenticated route
app.put<Record<string, never>, CounterResponse, CounterUpdateRequest>(
  "/api/counter",
  (req, res) => {
    counter.add(req.body.value);
    res.send({ counter: counter.count });
  }
);

// authenticated route
app.get<Record<string, never>, CounterResponse>(
  "/api/counter/me",
  delegatedTokenAuth,
  (req, res) => {
    const sub = (req as unknown as JWTRequest).auth?.sub;
    if (!sub) {
      res.status(401);
      return;
    }

    const c = findOrAddCounter(sub);

    res.send({ counter: c.count });
  }
);

// authenticated route
app.post<Record<string, never>, CounterResponse>(
  "/api/counter/me",
  delegatedTokenAuth,
  async (req, res) => {
    const sub = (req as unknown as JWTRequest).auth?.sub;
    if (!sub) {
      await res.status(401);
      return;
    }

    const c = findOrAddCounter(sub);

    c.increment();

    await res.send({ counter: c.count });
  }
);

export default app;

Last updated