New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

check-types-mini

Package Overview
Dependencies
Maintainers
1
Versions
198
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

check-types-mini

Check the types of your options object's values after user has customised them

  • 2.6.0
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
1.9K
decreased by-7.64%
Maintainers
1
Weekly downloads
 
Created
Source

check-types-mini

Check the types of your options object's values after user has customised them

Link to npm page Build Status Coverage Status bitHound Overall Score bitHound Dependencies bitHound Dev Dependencies Known Vulnerabilities Downloads/Month View dependencies as 2D chart Test in browser

Table of Contents

Install

$ npm i -S check-types-mini

Transpiled code (ES5) is served.

Idea

Imagine you have a library where you let users set the options object which comes as one of the input arguments.

Here's a challenge: how do you check (and throw) errors, easily, when users set your options to wrong things?

Answer: this library. It does all the work validating the inputs, lets you customise the throw error messages (like below) and even lets you provide the schema, that is, array of allowed types that each options key's value should be in.

For example, here's a typical throw error generated by this library:

TypeError: fancyLibrary/fancyFunction(): [THROW_ID_01] opts.placeholder was customised to "false" which is not boolean but string

Originally this library started as a function within one of my libraries. When I was about to copy-paste the thing into another library, I stopped and put that into a separate library, this library. I'm glad I did it, because already 7 of my libraries depend on it, and improving check-types I improve my other libraries. DRY at its best.

The point of check-types-mini is to save your time creating new libraries. Every library that has options object will need some type checks if you let user tinker with it.

API

checkTypes(obj[, ref, opts])

As a result, it throws TypeErrors for you, containing your custom message which you optionally set via arguments:

Input argumentTypeObligatory?Description
objPlain objectyesOptions object after user's customisation
refPlain objectno^Default options - used to compare the types
optsPlain objectnoOptional options go here.

^ref can be null or undefined if all keys are set via opts.schema (see below).

Options object

options object's keyTypeObligatory?DefaultDescription
{
ignoreKeysArray or Stringno[] (empty array)Instructs to skip all and any checks on keys, specified in this array. Put them as strings.
acceptArraysBooleannofalseIf it's set to true, value can be array of elements, same type as reference.
acceptArraysIgnoreArray of strings or Stringno[] (empty array)If you want to ignore acceptArrays on certain keys, pass them in an array here.
enforceStrictKeysetBooleannotrueIf it's set to true, your object must not have any unique keys that reference object (and/or schema) does not have.
schemaPlain objectno{}You can set arrays of types for each key, overriding the reference object. This allows you more precision and enforcing multiple types.
msgStringno A message to show. I like to include the name of the calling library, parent function and numeric throw ID.
optsVarNameStringnooptsHow is your options variable called? It does not matter much, but it's nicer to keep references consistent with your API documentation.
}

For example

The common pattern is,

  1. a) Define defaults object. Later it will be used to validate user's options, PLUS, if that's not enough, you can allow users to provide arrays of the matching type (set opts.acceptArrays to true)
  2. b) Alternatively, you can skip defaults object and provide schema for each key via opts.schema. Just stick an object there, as a value, with all keys. Put allowed types in an array.
  3. Object.assign cloned defaults onto the options object that comes from the input.
  4. call check-types-mini with the above.
  5. If input types mismatch, error will be thrown.
const checkTypes = require('check-types-mini')

function yourFunction (input, opts) {
  // declare defaults, so we can enforce types later:
  let defaults = {
    placeholder: false
  }
  // fill any settings with defaults if missing:
  opts = Object.assign({}, defaults, opts)

  // the check:
  checkTypes(opts, defaults, {msg: 'newLibrary/yourFunction(): [THROW_ID_01]', optsVarName: 'opts'})
  // ...
}

let res = yourFunction(1, {placeholder: 'zzz'})

// =>> [TypeError: 'newLibrary/yourFunction(): [THROW_ID_01] opts.placeholder was customised to "zzz" which is not boolean but string']

Sometimes you want to accept either a string (or type "X") or an arrays of strings (elements of type "X"). As long as ALL the elements within the array match the reference type, it's OK. For these cases set opts.acceptArrays to true.

This will throw:

const checkTypes = require('check-types-mini')
checkTypes(
  { // < input
    option1: 'setting1',
    option2: [true, true],
    option3: false
  },
  { // < reference
    option1: 'setting1',
    option2: false,
    option3: false
  }
)
// => Throws, because reference's `option2` is Boolean ("false") but input `option2` is array ("[true, true]").

But when we allow arrays of the matching type, it won't throw anymore:

const checkTypes = require('check-types-mini')
checkTypes(
  {
    option1: 'setting1',
    option2: ['setting3', 'setting4'],
    option3: false
  },
  {
    option1: 'setting1',
    option2: 'setting2',
    option3: false
  },
  {
    acceptArrays: true
  }
)
// => Does not throw, because we allow arrays full of a matching type

If you want, you can blacklist certain keys of your objects so that opts.acceptArrays will not apply to them. Just add keys into opts.acceptArraysIgnore array.

opts.enforceStrictKeyset

When I was coding a new major version of posthtml-ast-delete-object I had to update all the unit tests too. Previously, the settings were set using only one argument, Boolean-type. I had to change it to be a plain object. I noticed that when I missed updating some tests, their Booleans were Object.assigned into a default settings object and no alarm was being raised! That's not good.

Then I came up with the idea to enforce the keys of the object to match the reference and/or schema keys in options. It's on by default because I can't imagine how you would end up with settings object that does not match your default settings object, key-wise, but if you don't like that, feel free to turn it off. It's opts.enforceStrictKeyset Boolean flag.

opts.schema

Sometimes your API is more complex than a single type or array of them. Sometimes you want to allow, let's say, string or array of strings or null. What do you do?

Enter opts.schema. You can define all the types for particular key, as an array:

const checkTypes = require('check-types-mini')
checkTypes(
  {
    option1: 'setting1',
    option2: null
  },
  {
    option1: 'zz',
    option2: 'yy' // << notice, it's given as string in defaults object
  },
  {
    schema: {
      option2: ['stRing', null]
    }
  }
)
// => does not throw

The types are case-insensitive and come from type-detect, a Chai library:

  • object (meaning a plain object literal, nothing else)
  • array
  • string
  • null
  • and other usual types

The type values you put into opts.schema are not validated, on purpose, so please don't make typos.

Contributing

If you see anything incorrect whatsoever, do raise an issue. If you file a pull request, I'll do my best to merge it quickly. If you have any comments on the code, including ideas how to improve something, don't hesitate to contact me by email.

If something doesn't work as you wished or you don't understand the inner working of this library, do raise an issue. I'm happy to explain what's happening. Often some part of my README documentation is woolly, and I can't spot it myself. I need user feedback.

Also, if you miss a feature, request it by raising an issue as well.

I know it never happens but if you would ever forked it and worked on a new feature, before filing a pull request, please make sure code is following the rules set in .eslintrc and npm run test passes fine. It's basically an airbnb-base rules preset of eslint with few exceptions: 1. No semicolons. 2. Allow plus-plus in for loops. See ./eslintrc.

I dropped JS Standard because it misses many useful ESLint rules and has been neglected by its maintainers. At the moment, its ESLint version is six months old, missing one major release.

Licence

MIT License (MIT)

Copyright (c) 2017 Codsen Ltd, Roy Revelt

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Keywords

FAQs

Package last updated on 19 Sep 2017

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc