DEV Community

Discussion on: The Maybe data type in JavaScript

Collapse
 
wandersonalves profile image
Wanderson

My Either implementation:

type Either<T> = [Left, Right<T>]

Using it:

/**
   * Finds the first Document that matchs the params
   * @param params.filter Object used to filter Documents
   * @param params.fieldsToShow Object containing the fields to return from the Documents
   * @param params.databaseName Set this to query on another database in the current mongo connection
   * @param params.throwErrors Enable classical try/catch way of handling errors
   * @returns A Promise with a single Document
   */
  findOne(params: IFindOneParams<Interface, false>): Promise<Either<Interface>>;
  findOne(params: IFindOneParams<Interface, true>): Promise<Interface>;
  findOne(params: IFindOneParams<Interface, boolean>): Promise<Either<Interface> | Interface> {
    return new Promise(async (resolve, reject) => {
      try {
        const _model = this.getModel(params.databaseName);
        const result = (await _model.findOne(params.filter, params.fieldsToShow).lean(true)) as any;
        if (params.throwErrors) {
          resolve(result);
        }
        resolve([null, result]);
      } catch (e) {
        const exception = new GenericException({ name: e.name, message: e.message });
        if (params.throwErrors) {
          reject(exception);
        }
        resolve([exception, null]);
      }
    });
  }

In another place using express

/** some code **/
const [insertError, insertSuccess] = await this.promotionService.insert({
      entity: promotion,
      databaseName: validationSuccess._id.toString(),
    });
    res.status(insertError ? insertError.statusCode : CREATED).send(insertError ? insertError.formatError() : insertSuccess);
Collapse
 
aminnairi profile image
Amin

I didn't know you could overload your function signature like that in TypeScript... Looking dope!

In my opinion, since you need to keep track of your errors as well as your result in an Either type, it would have been like that in my understanding:

type Either <A, B> = Left<A> | Right<B>

What do you think?