@pgds/mongodb
v0.4.2
Published
mongo db interface for pgds services
Readme
hiot-mongodb
connectToDb
Function for connecting to a mongodb database. It returns a promise that resolves to a Db object. If a locator is provided, it will add the db to the locator object. Can be used to connect to multiple databases.
interface ConnectOptions {
host: string;
port: number | string;
database: string;
replicaSet?: string;
logger: LoggerLike;
/** Optional if connecting to additional databases. Will add the db to the locator object if provided */
locator?: Locator;
/* Optional if database needs to be accessed from somewhere in the code, defaults to the database name */
databaseIdentifier?: string;
}
function connectToDb(options: ConnectOptions): Promise<Db>;Usage
const db = await connectToDb({
host: "localhost",
port: 27017,
database: "test",
logger,
locator,
});connectToDb returns the Db for the connected database. If needed, it can also be retrieved using the getDatabase function. The repository class uses getDatabase internally to get the database when needed (if a database identifier (e.g. database name) is provided).
/** @param databaseIdentifier - database identifier, defaults to name of the database */
function getDatabase(databaseIdentifier: string): Db;
const db = getDatabase("test");To close the database connect, use the closeDbs function.
function closeDbs(): Promise<void>;Database indexes
These utilities create indexes on a collection. Both accept either a database identifier or a Db object as the optional final argument. If omitted, they use the first connected database.
createDatabaseIndexes
Creates an index for each key specification in indexes.
function createDatabaseIndexes(collection: string, indexes: any[], databaseNameOrDb?: string | Db): Promise<string[]>;The returned promise resolves to the names of the created indexes. Index creation errors are logged and result in an empty array.
await createDatabaseIndexes("users", [{ organizationId: 1 }, { userId: 1 }], accountsDb);createLocaleDatabaseIndexes
Creates the specified index once per locale, using a locale-specific collation with strength 2 and the name locale_<keys>_<hash>_<locale>.
keyscontains field names and directions in order. Characters outside ASCII letters, numbers,_,.and-are replaced by_, and the result is truncated to 60 characters.hashis the first 16 hex characters of the SHA-256 digest of the BSON serialization of{ index }. It helps distinguish ambiguous or truncated names.
For example, { name: 1, _id: 1 } with locale en produces locale_name_1__id_1_a84828bf2dcfbc10_en. Use the same specification representation when recreating an index; equivalent specifications expressed differently can produce different names.
Existing indexes created with previous naming schemes are not renamed or removed. MongoDB can reject an equivalent index with a different name, so migrate those indexes deliberately before recreating them with the new names.
function createLocaleDatabaseIndexes(
collection: string,
index: any,
locales: string[],
databaseNameOrDb?: string | Db
): Promise<string[]>;The returned promise resolves to the names of the created indexes. Index creation errors are logged and result in an empty array.
await createLocaleDatabaseIndexes("users", { name: 1 }, ["en", "sv"], accountsDb);Repository
A class that provides a simple interface for interacting with a mongodb collection. Fully typed and supports all CRUD operations. It can be extended if needed (most likely not). It adds authorization to the query if a user is provided. This functionality is done by its getAuthQuery function, which can be overriden if needed. It can connect to a database using a database identifier or a Db object (e.g. if the database is connected using connectToDb in app.ts using configs, the same configs can be used as the database identifier).
constructor Repository<T>(databaseIdentifierOrDb: string | Db, collectionName: string, clazz?: (new (...args: any[]) => T) | undefined): Repository<T>Usage
const usersRepo = new Repository("accounts-api", "users", User);
const user = await usersRepo.getById("123");
// ... or
class UsersRepo extends Repository<User> {
constructor() {
super("accounts-api", "users", User);
}
}
const usersRepo = new UsersRepo();
const user = await usersRepo.asUser(req.user).getById("123");
// .. or
const usersRepo = new Repository(accountsDb, "users", User);
const user = await usersRepo.asUser(req.user).getById("123");Functions:
save(entity: T, user?: ReqUser): Promise<T>
saveMany(entities: T[], user?: ReqUser): Promise<T[] | null>
getById(id: string, user?: ReqUser): Promise<T | null>
getByQuery(query: any, sort?: any, size?: number | undefined, page?: number | undefined, user?: ReqUser): Promise<T[]>
getTotalCount(query: any, user?: ReqUser): Promise<number>
getByQueryWithTotalCount(query: any, sort?: any, size?: number, page?: number, user?: ReqUser): Promise<{ totalCount: number; data: T[]; }>
update(id: string, entity: DeepPartial<T>, user?: ReqUser): Promise<T | null>
updateByQuery(query: any, entity: DeepPartial<T>, user?: ReqUser): Promise<number>
remove(id: string, user?: ReqUser): Promise<boolean>
removeByQuery(query: any, user?: ReqUser): Promise<boolean>
/** exported from mongodb */
aggregate(pipeline: Object[]): AggregationCursor<any>;
aggregate(pipeline: Object[], options?: CollectionAggregationOptions): AggregationCursor<any>;
asUser(user: ReqUser): Repository<T>asUser function
A short hand function for running a function as a specific user (it will add the user as the last of any subsequent function call). It is mostly for code readability's sake.
const thing = await thingsRepo.asUser(req.user).getByQuery({ _id: req.params.thingId });This is the same as doing:
const thing = await thingsRepo.getByQuery({ _id: req.params.thingId }, undefined, undefined, undefined, req.user);Test utils
insert
Port of https://github.com/hiotlabs/hiot-mongodb-js/blob/master/lib/test/insert.js which is used in most services. It inserts data into collections.
function insert(
db: Db | string,
context: {
[collectionName: string]: any[];
}
): Promise<void>;insert("accounts-api", {
users: [{ _id: "123", name: "John" }],
things: [{ _id: "456", name: "Thing" }],
});
// or
insert(accountsDb, {
users: [{ _id: "123", name: "John" }],
things: [{ _id: "456", name: "Thing" }],
});getAuthQuery
When user is provided to a repository function, the getAuthQuery function does the following (if not overridden):
For
globalusers- Returns any data matching the original query
For users with the ability to manage their organization (has
canManageOrganizationactivity):- Returns data belonging to the user's organization
- Returns data shared with the user's organization
For regular users (does not have
canManageOrganizationactivity):- Returns data within the user's organization owned by the user
- Returns data within the user's organization shared directly with the user
Running tests
Since the tests rely on mongodb, you can either run the tests using the Docker Compose file provided or by running mongodb locally.
Docker Compose
yarn test:docker (or docker compose run hiot-mongodb)alternatively
docker compose run hiot-mongodb bash && yarn tLocally
If you have mongodb installed locally you can run the tests using the following commands:
mongod
yarn testBuilding and publishing
// Check out any untracked/ignored files (e.g. previously built files)
yarn clean
// Install dependencies
yarn install
// Build
yarn build
// Make sure tests pass (see above)
yarn test:docker
// Publish
npm publish --access public
// Or pack (for testing)
yarn pack