{"id":15603392,"url":"https://github.com/codemeasandwich/pick-n-mix","last_synced_at":"2025-03-29T13:25:32.916Z","repository":{"id":57150162,"uuid":"105248168","full_name":"codemeasandwich/pick-n-mix","owner":"codemeasandwich","description":"a set of tools, untils and polyfulls for writing declarative javascript apps","archived":false,"fork":false,"pushed_at":"2017-11-27T12:26:05.000Z","size":26,"stargazers_count":1,"open_issues_count":2,"forks_count":1,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-03-08T22:17:23.446Z","etag":null,"topics":["error","error-handling","javascript","try-catch"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/codemeasandwich.png","metadata":{"files":{"readme":"ReadMe.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2017-09-29T08:22:06.000Z","updated_at":"2017-11-20T12:15:16.000Z","dependencies_parsed_at":"2022-09-03T17:51:50.971Z","dependency_job_id":null,"html_url":"https://github.com/codemeasandwich/pick-n-mix","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/codemeasandwich%2Fpick-n-mix","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/codemeasandwich%2Fpick-n-mix/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/codemeasandwich%2Fpick-n-mix/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/codemeasandwich%2Fpick-n-mix/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/codemeasandwich","download_url":"https://codeload.github.com/codemeasandwich/pick-n-mix/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":246188962,"owners_count":20737784,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["error","error-handling","javascript","try-catch"],"created_at":"2024-10-03T03:03:05.710Z","updated_at":"2025-03-29T13:25:32.888Z","avatar_url":"https://github.com/codemeasandwich.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# pick-n-mix\n## a set of tools, untils and polyfulls for writing declarative javascript apps\n\n- [errors](#errors)\n    + [Example:](#example)\n- [deepRequire](#deeprequire)\n- [promisify](#promisify)\n- [graphql Scheam Builder](#graphql-scheam-builder)\n  * [Overview](#overview)\n  * [How to use](#how-to-use)\n  * [Using the above code snippets](#using-the-above-code-snippets)\n\n# errors\nA extension mechanism for JavaScript errors\n\nThe **`errors.registry`** functions registers custom Error constructors\n\n1 **registry** should be passed a `String` **or** `Array` of strings. Representing the names of the errors you want generated.\n\n2 The generated Errors has a signature if\n* message - `String`. The description of the problem\n* args - `mix`. Any arguments that were used\n* rootCause - `Error`. A lower level error are is being wrapped\n\n3 The new Error Object will have some more attributes\n* type - `String`. The name of this type of Error\n* fileName - `String`. The file name - where this error was created\n* lineNumber - `Number`. The line number - where this error was created\n* columnNumber - `Number`. The column number - where this error was created\n* functionName - `String`. The function name - where this error was created\n* createdAt - `Number`. The time the error was create based on hosts time settings.\n* rootCause - `Error`. Error that trigger this error. `undefined` if not set\n* args - `mix`. Any arguments that were used. `undefined` if not set\n* processId - `Number`. The Node process ID if create on a server.  `undefined` **if created in brower**\n* userAgent - `String`. The user agent. `undefined` **if created in Node**\n  * This can be set on Node by using `err.setUserAgent(req.headers['user-agent'])`\n\n\n### Example:\n\n#### ES6 modules\nDuring your app startup\n```JS\nimport registry from 'pick-n-mix/errors'\n\nregistry(\"BadInput\");\n```\n\nAny where you wish to use it\n```JS\nimport { BadInputError } from 'pick-n-mix/errors'\n//...\nif( ! input){\n  throw new BadInputError(\"missing input\",input)\n}\n//...\n```\n\n#### AMD / Node modules\nDuring your startup\n```JS\nvar registry = require('pick-n-mix/errors').registry\n\nregistry(\"Authorization\");\n```\n\nAny where you wish to use it\n```JS\nvar errors = require('pick-n-mix/errors')\nvar AuthorizationError = errors.AuthorizationError\n//...\nif( ! ok){\n  throw new AuthorizationError(\"Bad password\",user)\n}\n//...\n```\n\n**🎉 Pro Tip:** You can pass a descriptive string to registry to indicate error subtype\n\n```JS\nregistry(['Range\u003eInvalidArgument','Internal']);\n\nvar invalidErr = new InvalidArgumentError(\"...\")\n\ninvalidErr instanceof InvalidArgumentError // true\ninvalidErr instanceof RangeError           // true\ninvalidErr instanceof Error                // true\n\nvar internalErr = new InternalError(\"...\")\n\ninternalErr instanceof InternalError // true\ninternalErr instanceof RangeError    // false\ninternalErr instanceof Error         // true\n```\n\n# utils\n\n## deepRequire\n\n**deepRequire** will require all sub-files in a folder as a nasted Object.\n\nYou must supply the path to the folder\n`deepRequire(dirname)`\nYour can also pass an Array of file extensions. Default:`[\"js\"]`\n`deepRequire(dirname,exts)`\n\n### Example:\n\n    tools/\n     ├─ index.js\n     ├─rest/\n     │   ├─ get.js\n     │   └─ post.js\n     └─ list/\n         └─ points.js\n\nIn **tools.index.js**\n```JS\n// index.js start\nconst deepRequire = require('pick-n-mix/utils/deepRequire')\nmodule.exports = deepRequire(__dirname);\n// index.js end\n```\n\nIn you service code\n\n```JS\nconst tools = require('./tools')\n\ntools.rest.get()\n```\n\n## promisify\n\n**promisify** takes an Object with Async functions using callback functions and loops of the first level attributes wrapping them in a Promise\n\nYou must supply the object holding the Async functions. It will then wrap all attributes\n\n`promisify(obj)`\n\nYour can also pass an Array of attributes **not** to wrap.\n\n`promisify(obj,[\"skip\"])`\n\n### Example:\n\nSetup you worker object with two function attributes \"**get_pic**\" and \"**name**\"\n```JS\nconst user = {\n  get_pic:function(next){\n    $.ajax({\n      url: \"/user/pic/meta\",\n      error: function(xhr,status,error){\n        next(error)\n      },\n      success: function(result){\n        next(null,result)\n      }\n    });\n  },\n  name: function(){ return \"Bob\" }\n}\n```\n\nWrap the worker but skip the \"name\" function\n```JS\nconst promisify = require('pick-n-mix/utils/promisify')\nconst userP = promisify(user,[\"name\"]);\n```\n\nUse your newly wrapped worker\n\n```JS\nuserP.get_pic().then( function(result){\n  console.log(result)\n}).catch( function(err){\n  console.error(err)\n})\n\nconsole.log(userP.name()) // \"bob\"\n```\n\n# graphql Scheam Builder\n\n## Overview\n\nEach custom graphql **type** will have its own file.\n\nThe file looks like\n```JS\nmodule.exports = {\n  description:\"Error info\",\n  model:`{\n    type:String!, // type of error\n    message:String!, // 'error message'\n    args:String!,//arguments\n    trace:String!// 'stack trace'\n  }`\n}\n```\nThis will be outputted\n\n```\n # Error info\n #* **type** - type of error,\n #* **message** - 'error message',\n #* **args** - arguments,\n #* **trace** - 'stack trace'\n type Error{\n     type:String,\n      message:String,\n      args:String,\n      trace:String\n     }\n```\n**🛈 Things to know:**\n* Each type will **also** have a `Input` version generated for convenience.\n```\n # Error info\n #* **type** - type of error,\n #* **message** - 'error message',\n #* **args** - arguments,\n #* **trace** - 'stack trace'\n input InputError{\n     type:String,\n      message:String,\n      args:String,\n      trace:String\n     }\n```\n\n\n## How to use\n\nScheam Builder is designed to be use with [deepRequire](https://github.com/codemeasandwich/pick-n-mix/tree/master/utils) to pull in your types.\n\n### An Example schemas:\n\n    sample/\n     ├─ index.js\n     ├─ Error.js\n     ├─ partys.js\n     └─ accounts/\n         └─ user/\n             ├─ index.js\n             └─ item.js\n\n[Example Source](https://github.com/codemeasandwich/pick-n-mix/tree/master/schemaQL/sample)\n\n\nYou will need to specify the \"Query\" and \"Mutation\" strings\n\n```\nconst Query = `\n  # A GraphQL API for my App\n   type Query {\n     readUser(id:String):user,\n     config:Config,\n   }`\n\nconst Mutation = `\n   type Mutation {\n     logError(type:String!, message:String!,args:String!,trace:String!):Error\n   }\n`\n```\n\n`Query` and `Mutation` Api function will map to the same object\n\n```\nvar root = {\n// Query\nreadUser: (args)=\u003e db.getUser({_id:args.id}),\nconfig: () =\u003e fs.readFileAsync(__dirname + \"/config.json\"),\n\n// Mutation\nlogError: (args)=\u003e{\n  const type      = args.type;\n  const message   = args.message;\n  const errorArgs = args.args;\n  const trace     = args.trace;\n\n  return db.saveError(message,{type,errorArgs},trace)\n           .then( x =\u003e args ) // return the error back to use\n  },\n}\n\n```\n\n## Using the above code snippets\n\n```JS\n\nconst deepRequire = require('pick-n-mix/utils/deepRequire');\nconst schemas = deepRequire(\"./My_schemas_dir\");\n\nconst schemaQL    = require(\"pick-n-mix/schemaQL\");\nconst schemaTypes = schemaQL(schemas);\n\nconst buildSchema = require('graphql').buildSchema;\nconst schema = buildSchema(schemaTypes\n                            + \" \" + Query  \n                            + \" \" +  Mutation)\n\n// ================== Express Server\n// =================================\n\nconst graphqlHTTP = require('express-graphql');\nconst express     = require('express');\n\nconst app = express();\n\n// ======================== Graph QL\n// =================================\n\n  app.use('/graphql', graphqlHTTP({\n    schema: schema,    rootValue: root,    graphiql: true,\n  }));\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcodemeasandwich%2Fpick-n-mix","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcodemeasandwich%2Fpick-n-mix","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcodemeasandwich%2Fpick-n-mix/lists"}