NPM install
npm install @agile-learning-institute/mentorhub-ts-api-utils
NOTE: This adds the package to your project’s dependencies. Ensure your project uses Node.js 16+ and TypeScript 4.9+ for compatibility.
These utilities provide a unified and reusable set of tools to streamline development for MentorHub's TypeScript-based APIs. They abstract common operations, reduce boilerplate code, and enforce best practices for configuration, request handling, and MongoDB interaction.
This is a collection of simple Express utilities:
- Token() decodes and constructs a Roles Based Access Control (RBAC) token
- Breadcrumb(token) builds the breadcrumb used when updating the database
All API will be secured with industry standard bearer tokens used to implement Role Based Access Control (RBAC). The create_token method will decode the token and extract claims for a user_id and roles, throwing an exception if the token is not found or not properly encoded.
{
"user_id": "The users PersonID",
"roles": ["Staff", "Mentor", "Member"]
}
Valid roles are listed in the mentorhub-mongodb repo's enumerators file but the roles listed above are the only one's currently used in the mentorHub platform.
All database collections include a lastModified "breadcrumb" property used to track changes over time. This breadcrumb should be provided to all database write functions. The breadcrumb has the following properties:
{
"atTime": "date-time the document was last modified",
"byUser": "UserID claim from the access token",
"fromIp": "IP Address the request originated at",
"correlationId": "A correlationID to use in logging"
}
Here is how these methods are used in a Express Controller
import { Request, Response } from 'express';
import { Token, decodeToken, Breadcrumb, createBreadcrumb }
from '@agile-learning-institute/mentorhub-ts-api-utils';
export default class SomeController {
public getSomething = (req: Request, res: Response) => {
const token: Token = decodeToken(req);
const breadcrumb: Breadcrumb = createBreadcrumb(token);
// Do something with token, breadcrumb
if (!token.roles.includes("Staff")) throw new Error("Access Denied");
const updateData = {"some":"update"};
updateData.lastSaved = breadcrumb;
This is collection of utilities to support API Configuration in a standard way
- Config handles configuration values
- ConfigController is a Express request handler
Standard Config
Standard mentorHub configuration values. Configurations are managed in a consistent way favoring file based configuration values, then environment configuration values, and then default values. See the Config.ts for details on the configuration values.
import { Config } from '@agile-learning-institute/mentorhub-ts-api-utils';
config: Config = Config.getInstance();
console.log(`Built at ${config.BUILT_AT}`)
This is a simple express request handler to be used to expose the config data on a config endpoint.
import { ConfigController } from '@agile-learning-institute/mentorhub-ts-api-utils';config';
const app = express();
const configController = new ConfigController();
app.get('/api/config/', (req, res) => configController.getConfig(req, res));
Simple wrappers for MongoIO and a Config Initializer.
- getInstance() returns the singleton object
- connect() connects to the database and initializes values in the Config singleton
- disconnect gracefully disconnects from the database
- getDocuments gets a list of documents
- getDocument gets a single document by id
- createDocument creates a new document
- updateDocument updates an existing document (by id)
- deleteDocument hard deletes a document (by id)
- [encodeDocument]
Get a reference to the Singleton object
import { MongoIO } from '@agile-learning-institute/mentorhub-ts-api-utils';
mongoIO = MongoIO.getInstance();
This method will connect to the Mongo Database, and load the config.versions[]
and config.enumerators{}
properties. The enumerators loaded are based on the current version of the collection provided.
mongoIO = MongoIO.getInstance();
mongoIO.connect(config.MAIN_COLLECTION_NAME)
This method will disconnect from the database in a graceful way. You should call this method when the server process is ending.
mongoIO = MongoIO.getInstance()
mongoIO.disconnect()
This is a convenience method to get a list of documents based on Mongo Match, project, and sort order parameters.
const match = { name: { $regex: query } };
const project = { _id: 1, name: 1 };
const order = [{ name: 1 }];
const documents = mongoIO.getDocuments("COLLECTION_NAME", match, project, order);
This is a convenience method to get a single document based on ID
document = mongoIO.getDocument("COLLECTION_NAME", "_ID String");
This is a convenient method for creating a single document
document = {"foo":"bar"};
created = mongoIO.createDocument("COLLECTION_NAME", document);
This is a convenience method for updating a single document based on ID
id = "24-byte-id";
patch = {"foo":"bar"};
updated = mongoIO.updateDocument("COLLECTION_NAME", id, patch);
This is a convenience method for deleting a document based on ID. This is an actual live delete, not a soft delete.
id = "24-byte-id";
updated = mongoIO.deleteDocument("COLLECTION_NAME", id);
This is a convenience method for encoding ObjectID and Date properties of a document
document = {idProp: "123456789012345678901234", dateProp: "2009-10-11T12:34:56.000Z" };
encodeDocument(document, ["idProp"], ["dateProp"]);
If you want to contribute to this library, here are the instructions.
- Mongo Compass Useful for visually exploring and managing MongoDB collections.
- Step CI Ideal for black-box testing APIs to validate behavior against specifications.
npm install
npm run clean
npm run build
npm run test
NOTE: The MongoIO unit tests are actually integration tests that expect the MentorHub MongoDB to be found at the default configuration. If you have the MentorHub developers edition installed you can use mh up mongodb
to start this database.
npm run lint
npm version patch
NOTE: CI will run build
, test
, and publish
to deploy new versions.
npm run publish-it