@hiotlabs/hiot-mongodb
v0.1.1
Published
mongo db interface for Hiotlabs services
Downloads
132
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>;
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>
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[], callback: MongoCallback<any[]>): AggregationCursor<any>;
aggregate(pipeline: Object[], options?: CollectionAggregationOptions, callback?: MongoCallback<any[]>): 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
global
users- Returns any data matching the original query
For users with the ability to manage their organization (has
canManageOrganization
activity):- Returns data belonging to the user's organization
- Returns data shared with the user's organization
For regular users (does not have
canManageOrganization
activity):- 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
docker-compose run hiot-mongodb (or run test:docker)
alternatively
docker-compose run hiot-mongodb bash && yarn t
Locally
If you have mongodb installed locally you can run the tests using the following commands:
mongod
yarn t
Building and publishing
// Install dependencies
yarn install
// Build
tsc
// Make sure tests pass (see above)
// Publish
npm publish --access public