CRBT-Team/Purplet

View on GitHub
packages/rest/src/route-group.js

Summary

Maintainability
A
0 mins
Test Coverage
/**
 * This function is written very dangerously, but since the only instance of this function is called
 * via the code generated by `scripts/gen-routes.js` in `routes.generated.ts`, it should be safe.
 *
 * I use an ES5 class since I can manually build the prototype using a for loop, instead of using a
 * ton of arrow functions and `Object.fromEntries` and so on. I can only assume that this way is
 * faster, but I don't actually know.
 *
 * There is a d.ts file here that has a strict type declaration that maps an object to a class with
 * per-function input and output types via `discord-api-types`, this is the JS implementation.
 *
 * @param {Record<
 *   string,
 *   | { route: string; method: string }
 *   | { route: (...args: string[]) => string; params: string; method: string }
 * >} routes
 *   An mapping of route function names to route description objects. A description object has a
 *   `method` for the method, and then a `route` with the endpoint string. If `route` is a function,
 *   you must also specify a `params` property with a list of param names, which get passed to
 *   `route` in the order you specify.
 * @returns {any} (d.ts file has this type set properly)
 */
export function group(routes) {
  function RouteGroup(rest) {
    this.rest = rest;
  }

  for (const routeName in routes) {
    const { route, params, method, auth } = routes[routeName];
    RouteGroup.prototype[routeName] = function (request = {}) {
      const endpoint =
        typeof route === 'string' ? route : route(...params.map(param => request[param]));

      return this.rest.request(endpoint, { method, auth, ...request });
    };
  }

  return RouteGroup;
}