Skip to content

Commit

Permalink
fix: improve error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
IamSebastianDev committed Dec 8, 2022
1 parent bb74c24 commit 8fb35b4
Showing 1 changed file with 16 additions and 7 deletions.
23 changes: 16 additions & 7 deletions src/lib/Db/Collection.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
/** @format */

import { __root, safeAsyncAbort, isTruthy, sortByProperty, isDocument } from '../../utils';
import { __root, safeAsyncAbort, isTruthy, sortByProperty, isDocument, FlotsamValidationError } from '../../utils';
import { Flotsam } from './Flotsam';
import { readdir, mkdir, rm, readFile, writeFile } from 'node:fs/promises';
import { existsSync } from 'node:fs';
import { existsSync, unwatchFile } from 'node:fs';
import { ObjectId } from './ObjectId';
import { JSONDocument } from './JSONDocument';
import { resolve } from 'node:path';
import { Queue } from './Queue';
import type { Document, Rejector, FindOptions, FindByProperty, DocumentInit, Validator } from '../../types';
import { evaluateFindOptions } from './evaluateFindOptions';
import { Crypto } from './Crypto';
import { FlotsamError } from '../../utils/Errors/FlotsamError';

/**
* @Class
Expand Down Expand Up @@ -141,6 +142,12 @@ export class Collection<T extends Record<string, unknown>> {

private rejector(reject: Rejector): Rejector {
return (error: unknown) => {
if (!FlotsamError.validate(error)) {
return;
}

error.reported = true;

this.ctx.emit('error', (error as Error).message);
reject(error);
};
Expand Down Expand Up @@ -803,18 +810,20 @@ export class Collection<T extends Record<string, unknown>> {
private async update(document: Document<T>, data: Partial<T>): Promise<Document<T>> {
return this.#queue.enqueue(
new Promise(async (res, rej) => {
safeAsyncAbort(this.rejector(rej), async () => {
const updated = new JSONDocument(
{ _id: document.id, _: { ...document, ...data } },
this.validationStrategy
);

let content = updated.toFile();
if (this.#crypt) content = this.#crypt.encrypt(content);
let content = updated.toFile();
if (this.#crypt) content = this.#crypt.encrypt(content);

await writeFile(resolve(this.#dir, document.id), content, 'utf8');
this.#documents.set(document.id, updated);
await writeFile(resolve(this.#dir, document.id), content, 'utf8');
this.#documents.set(document.id, updated);

return res(updated.toDoc());
return res(updated.toDoc());
});
})
);
}
Expand Down

0 comments on commit 8fb35b4

Please sign in to comment.