{"_id":"@cakasim/smart-results","_rev":"1-773afbddea5775a255b353f25f31ba81","name":"@cakasim/smart-results","dist-tags":{"latest":"0.1.0"},"versions":{"0.1.0":{"name":"@cakasim/smart-results","description":"Simple library for avoiding use of exceptions.","version":"0.1.0","author":{"name":"Fabian Böttcher","email":"me@cakasim.de"},"license":"MIT","repository":{"type":"git","url":"https://github.com/Cakasim/js-smart-results.git"},"homepage":"https://cakasim.de/","keywords":["rust","option","result"],"main":"dist/index.js","scripts":{"test":"jest --verbose","coverage":"jest --coverage","build":"rm -rf dist && tsc"},"devDependencies":{"@types/jest":"^26.0.15","jest":"^26.6.1","ts-jest":"^26.4.2","typescript":"^4.0.3"},"licenseText":"MIT License\n\nCopyright (c) 2020 Fabian Böttcher\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n","_id":"@cakasim/smart-results@0.1.0","dist":{"shasum":"bef4b3c617a5313282b5658b2f41868aab5b9039","integrity":"sha512-WnZnYLlzyg/JBtRn1VRb8haNS6gnFGUkouSIcv292LBqCCnqKHitqQWnS97XW2rBftFUk12e29nykcPDwc/B+A==","tarball":"https://registry.npmjs.org/@cakasim/smart-results/-/smart-results-0.1.0.tgz","fileCount":14,"unpackedSize":20138,"npm-signature":"-----BEGIN PGP SIGNATURE-----\r\nVersion: OpenPGP.js v3.0.13\r\nComment: https://openpgpjs.org\r\n\r\nwsFcBAEBCAAQBQJfla3wCRA9TVsSAnZWagAA01AP/08k0KXJN6jiSaqstg0i\nnCOyDtzdl8JdtRwpB8T63jPiKR7q+31NSJdHhTidQsFNXykpx+Gc4wPrKflA\n+44kZD2yC+t5kzL3jHJmC+CN7Y0XnB0Xa6uLaOWkF2k1S19zJ5VIuToPM4r2\n6AFaiZ6wcI48IWVjYSTl898GDDXvkt/zJnp8ezbpqrNuJccXGbD67YKhvRRW\ntppWAsBLOWvztw9/TQn2xKly/YitZ0mA4BRz9OB8braHRZOvI/8BswrojDQd\naB3Mq8y5FVo+GyEw3TTkmLFbSBKPx+pXoH+yArOy41UZMmCZSxNlnRDWvJ7f\nIEE9zG4w1BMqCvBtW7GegnknYQ9EpjzlwZPNBmanE4ZaEhTde1XPiDenamCQ\nxxEBn3DEyrh6dnuKpSGJICImTlAPvziBvcdojWXl08oXVfwnL8XL04QWLZhC\n6u72tDmTFYXaJEHAEZADC7zshbXcaTMKGd+qgIFOUjW1hYnsXj77Ehy3Jl7l\nbttWJ0Frp8AUtXNdqlZ9BrPTGVisIa06fYVsQUBYxFkfIKKrZYI9Vx5O0JdG\npHyGnFW62dSAXzWcJ+GO3CTLSIfMctbXVso/jSyUkiboiG/KgLgR5TcSFMpi\nv5AbRGGXDl/eyVQVET9VxC/oZmh+5Isjc5Pb9JEX9lGak+RS/Ra96vA2SObB\nwkfW\r\n=JxTD\r\n-----END PGP SIGNATURE-----\r\n","signatures":[{"keyid":"SHA256:jl3bwswu80PjjokCgh0o2w5c2U4LhQAE57gj9cz1kzA","sig":"MEUCIAbEv+LKuNjk2/CZkDdevJB0NkV3Dpd9Lh4znQrQH38lAiEAlPjQyXXfFSp8f3I77OfT3iMKcTNJV3nf1KYQRPXpOnQ="}]},"maintainers":[{"name":"cakasim","email":"me@cakasim.de"}],"_npmUser":{"name":"cakasim","email":"me@cakasim.de"},"directories":{},"_npmOperationalInternal":{"host":"s3://npm-registry-packages","tmp":"tmp/smart-results_0.1.0_1603644912362_0.3429212436404472"},"_hasShrinkwrap":false}},"time":{"created":"2020-10-25T16:55:12.319Z","0.1.0":"2020-10-25T16:55:12.489Z","modified":"2022-04-04T21:31:26.905Z"},"maintainers":[{"name":"cakasim","email":"me@cakasim.de"}],"description":"Simple library for avoiding use of exceptions.","homepage":"https://cakasim.de/","keywords":["rust","option","result"],"repository":{"type":"git","url":"https://github.com/Cakasim/js-smart-results.git"},"author":{"name":"Fabian Böttcher","email":"me@cakasim.de"},"license":"MIT","readme":"Smart Results for JS\n====================\n\n[![LICENSE](https://img.shields.io/github/license/Cakasim/js-smart-results.svg)](LICENSE)\n\n<!-- [![CI Status](https://github.com/Cakasim/php-payone-sdk/workflows/CI/badge.svg?branch=develop)](https://github.com/Cakasim/php-payone-sdk/actions)\n[![Build Status](https://travis-ci.org/Cakasim/php-payone-sdk.svg?branch=develop)](https://travis-ci.org/Cakasim/php-payone-sdk)\n[![Scrutinizer Code Quality](https://scrutinizer-ci.com/g/Cakasim/php-payone-sdk/badges/quality-score.png?b=develop)](https://scrutinizer-ci.com/g/Cakasim/php-payone-sdk/?branch=develop)\n[![Coverage Status](https://coveralls.io/repos/github/Cakasim/php-payone-sdk/badge.svg?branch=develop)](https://coveralls.io/github/Cakasim/php-payone-sdk?branch=develop)\n[![LICENSE](https://img.shields.io/github/license/Cakasim/php-payone-sdk.svg)](LICENSE)\n[![Total Downloads](https://poser.pugx.org/cakasim/payone-sdk/downloads)](https://packagist.org/packages/cakasim/payone-sdk) -->\n\nIntroduction\n------------\n\nThis is just a small library to make error handling somewhat joy in TypeScript. It is heavily inspired by Rust and\nits great concepts about error handling.\n\nHow to Use?\n-----------\n\nCurrently there are two types you can mak use of:\n\n - `Option<T>` which is a union type of `Some<T>` and `None<T>`\n - `Result<T, E>` which is a union type of `Ok<T, E>` and `Err<T, E>`\n\nThe type `Option<T>` comes with two helper functions, `some(value)` and `none()`. You should use these functions to create an `Option<T>`.\nThe type `Result<T, E>` follows the same principle except that you will have `ok(value)` and `err(value)` to create it.\n\nThe following code provides a brief overview which helps understanding the concepts.\n\n```ts\nimport { Option, some, none, Result, ok, err } from '@cakasim/smart-results';\n\n// Just a simple type for us to play with\ntype Animal = {\n  name: string;\n};\n\n// Another type which holds metrics about an animal\ntype Metric = {\n  minSize: number;\n  maxSize: number;\n  isCarnivorous: boolean;\n  cutenessFactor: number;\n};\n\n// A pre-filled list of animals\nconst animals = new Map<number, Animal>([\n  [1, { name: 'Ape' }],\n  [2, { name: 'Dog' }],\n  [3, { name: 'Cat' }],\n  [4, { name: 'Pig' }],\n  [5, { name: 'Bird' }],\n])\n\n/**\n * Finds an animal in the list and returns an Option<Animal>\n * which holds a valid animal if we have found an entry or nothing\n * if there is no entry for the provided ID.\n *\n * @param id Animal ID.\n */\nfunction findAnimal(id: number): Option<Animal>\n{\n  // Get animal for provided ID, or undefined if ID is invalid\n  const animal = animals.get(id);\n\n  // Check if animal is not undefined and return either Some or None\n  return animal\n    ? some(animal)\n    : none();\n}\n\n/**\n * Fetches a metric dataset about the provided animal from an HTTP Rest API.\n * The return value is a Promise that (always) resolves to a Result<Metric, Error>.\n * If a metric could be loaded the result contains a valid Metric value.\n * Otherwise the result contains an Error value.\n *\n * @param animal The animal.\n */\nasync function fetchAnimalMetric(animal: Animal): Promise<Result<Metric, Error>>\n{\n  // Assume we are fetching actual data here\n  const response = await fetchAnimalMetricFromRestApi(animal);\n\n  // Check if the response code is good and return either Ok or Err\n  return response.statusCode === 200\n    ? ok(response.data as Metric)\n    : err(new Error(`Could not fetch from HTTP API, go status code ${response.statusCode}.`));\n}\n\n/**\n * This is the function that gets actually executed by someone.\n *\n * @param animalId Animal ID.\n */\nasync function printAnimalMetric(animalId: number)\n{\n  // Search for the animal, *expect* a None result and handle it by throwing the provided Error.\n  // If the result is Some no error will be thrown. Please note that `expect()` should be used\n  // carefully only if the exception case can be handled properly.\n  const animal = findAnimal(animalId).expect(() => new Error(`Cannot find animal for ID ${animalId}.`));\n\n  // metric is a Result<Metric, Error>, at this point we are forced to check for a valid result\n  const metric = await fetchAnimalMetric(animal);\n\n  if (metric.isErr()) {\n    // Handle the error case\n    console.error(`Failed to fetch data for animal ID ${animalId} with name ${animal.name} from REST API: ${metric.value.message}`);\n  } else {\n    // At this point metric.value is safe to use\n    console.log(`The metric for animal ID ${animalId} with name ${animal.name} is:`);\n    console.log(metric.value);\n  }\n}\n```\n","readmeFilename":"README.md"}