Skip to content

Function notes

Calum Dingwall edited this page Jun 1, 2022 · 6 revisions

Custom properties of Express objects

Express API

  • req: Request and request-related custom methods.
    • user: Logged-in user.
    • event: custom object with current event
      • key: Event key in db
      • name: Name of current event
    • authenticate: Custom method to check if a user is authenticated to access a page.
      • parameter accessLevel (int): Access level of page. (See .env for the values of accessLevel)
    • shortagent: Object containing ip, device, os, and browser of the request useragent.
    • requestTime: System time of the start of the current request. Used for logging/performance tracking.
  • res: Response and response-related custom methods.
    • redirect: Built-in function to redirect user. To send user an alert card, use custom query:
      • alert: Message to alert user. Usage: res.redirect('/path/to/redirect?alert=Hello world.'); Note: Spaces and special characters are automatically URL encoded.
      • type: Type of notification card to display. (See Front-end classes for more info.) Usage: res.redirect('/path/to/redirect?alert=Uh oh, error!&type=error')

Middleware

Custom middleware functions are located inside helpers/usefunctions.ts. This is to reduce clutter inside app.ts.

Internationalization (i18n)

helpers/i18n.ts handles loading locale messages from JSON files in the locales directory and exposes functions to obtain those messages from the rest of the code. The functions are added on to Express's req, res, and res.locals.

  • msg(name, parameters) - returns a plain message (everything HTML escaped)

  • msgUrl(name, parameters) - returns a URL-encoded message

  • msgJs(name, parameters) - returns a message encoded as a JS string (for embedding in Pug inline JS)

  • msgMarked(name, parameters) - returns a message with parsed markdown (safe HTML tags allowed)

  • locale - the locale/language of the request

  • getLocales() - returns an array with details about available locales

  • getLocaleName(locale, inLocale?) - returns the human readable name of a locale by its ID (en -> English), optionally in another locale

  • getLocaleDir(locale) - returns if the locale is either ltr or rtl

A locale id refers to an ISO 639-1 language code (like en or fr), optionally with a dash and a region code (like en-us or fr-ca). All locale ids are dealt with in lowercase.

Parameters

Parameters can be passed to message functions as an object. Keys in the message (written as {key}) will be replaced with the value of that key in the object.

Database

Database utilities are located inside utilities.ts. The module wraps database calls into async functions, without needing to manually define collections inside every route. Each method inside utilities.ts is documented with jsdoc.

  • Sample usage: const teams = await utilities.find('teams', {}, {$sort: {team_number: 1}});