1.0.10 • Published 12 months ago

result-generator v1.0.10

Weekly downloads
-
License
MIT
Repository
github
Last release
12 months ago

Result Generator

This is a convenient way to end an operation by either producing an error with an error message or success with a success message.

How to use it

Install

Run the following command in your terminal:

npm install --save-dev result-generator

Use it in your app

Import

import ResultGenerator from "result-generator";

Use in code

I added a real-world example for creating a SQL database table.

const resultGenerator = new ResultGenerator();

  async create() {
    const resultGenerator = new ResultGenerator();
    try {
      const [confirmation] = await this.connection.execute<ResultSetHeader>(
        `CREATE TABLE IF NOT EXISTS customers (
          customer_id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
          officer_id SMALLINT UNSIGNED NOT NULL,
          first_name VARCHAR(255) NOT NULL,
          last_name VARCHAR(255) NOT NULL,
          email VARCHAR(255) NOT NULL,
          PRIMARY KEY (customer_id),
          FOREIGN KEY (officer_id) REFERENCES officers(officer_id)
        );`
      );

      const success = resultGenerator.generateSuccess(
        JSON.stringify(confirmation)
      );

      return success;
    } catch (e) {
      const error = resultGenerator.generateError(e);
      return error;
    }
  }

This is how you use it to assert whether an operation has been successful or returned an error.

customersRouter.put("/:id", async (req, res) => {
  const customer = createCustomerFromHTTPRequest(req);
  try {
    const customersDatabase = await createCustomersDatabase();
    const putResult = await customersDatabase.put(customer);
    if (putResult.success) return res.json(putResult.data);
    else throw new Error(putResult.error.message);
  } catch (e) {
    if (e instanceof Error) return res.status(404).json(e);
  }
});

API

Methods signature

generateSuccess(data: string);
generateError(err: unknown);
1.0.10

12 months ago

1.0.9

12 months ago

1.0.8

12 months ago

1.0.7

12 months ago

1.0.6

12 months ago

1.0.5

12 months ago

1.0.4

12 months ago

1.0.3

12 months ago

1.0.2

12 months ago

1.0.1

12 months ago

1.0.0

12 months ago