I am attempting to modify the save
method so that it waits for this.collection.create()
to complete before running, in order to prevent a potential crash.
class UserRepository extends BaseRepository<User>
{
constructor()
{
super();
this.collection = this.db.collection('users');
this.collection.create().then(res => {
if (res.code === 200)
{
// collection successfully created
}
}).catch(err => {
if (err.code === 409)
{
// collection already exists
}
});
}
}
class BaseRepository<T>
{
protected db: Database = Container.get('db');
protected collection: DocumentCollection;
public save(model: T): void
{
this.collection.save(model);
}
}
Now, I can implement it like this:
const userRepository = new UserRepository();
userRepository.save(new User('username', 'password'));
I have considered two solutions:
- Execute
this.collection.create()
synchronously - Create a property named
isCollectionReady
and include a small loop in thesave
method to wait for the value ofisCollectionReady
to change to true.
Is there a more effective way to achieve this?