Master your input data like a pro!

Overview

This is an image

Master your input data like a pro!

✔️ Node.js & browser ✔️ Only 1kb! ✔️ Fully typed ✔️ No dependencies


Simple helper library which allows you to ensure the integrity and type safety of your app's input data.

It works by exposing a number of functions which check wether an unknown value is either a string, boolean, float, integer or object. You can also turn strings into numbers or booleans.

🚀 Getting started

npm

$ npm i primitive-parser

yarn

$ yarn add primitive-parser

💡 Examples

🕵 Make sure nasty user inputs do not reach your app.

// ...

import express from 'express'
import { getPositiveInteger } from 'primitive-parser'

// ...

app.get('/:user/:id', function (req, res) {
  const id = getPositiveInteger(req.params.id)
  if (!id) {
    return res.status(400)
  }

  // At this point, "id" is infered as "number".
  showUser(req, res, id)
})

// ...

🧛 Unsure about external events? No more.

import { getObject, getString } from 'primitive-parser'
import { useState } from 'react'
import SketchyInput from 'unknown-source'

const SafeInput = () => {
  const [value, setValue] = useState<string>('')

  const onValueChange = (sketchyEvent: any) => {
    const safeValue = getString(getObject(sketchyEvent)?.value)

    // Important over "!safeValue" since the latter returns "false" on valid empty strings.
    if (safeValue !== undefined) {
      // "safeValue" is inferred as "string" inside this block scope.
      setValue(safeValue)
    } else {
      // Error handling
    }
  }

  return <SketchyInput onValueChange={onValueChange} value={value} />
}

🍺 Full helper list

Check out the tests file for a full behavioural overview.

String

const getString = (value: unknown): string | undefined
getString('foo') // "foo"
getObject({ foo: 'bar' }) // undefined

Boolean

const getBoolean = (value: unknown): boolean | undefined
getBoolean('true') // undefined
getBoolean(true) // true

Boolean from String

const getBooleanFromString = (value: unknown): boolean | undefined
getBoolean('true') // true
getBoolean(true) // undefined

Float

const getFloat = (value: unknown): number | undefined
getFloat('12.34') // undefined
getFloat(12.34) // 12.34

Float from String

const getFloatFromString = (value: unknown): number | undefined
getFloat('12.34') // 12.34
getFloat(Infinity) // undefined
getFloat(12.34) // undefined

Integer

const getInteger = (value: unknown): number | undefined
getInteger('1234') // undefined
getInteger(12.34) // undefined
getFloat(1234) // 1234

Integer from string

const getIntegerFromString = (value: unknown): number | undefined
getIntegerFromString('1234') // 1234
getIntegerFromString(1234)) // undefined
getIntegerFromString(12.34) // undefined

Positive Integer

const getPositiveInteger = (value: unknown): number | undefined
getPositiveInteger('1') // undefined
getPositiveInteger(0) // undefined
getPositiveInteger(-1) // undefined
getPositiveInteger(1) // 1

Positive Integer from String

const getPositiveInteger = (value: unknown): number | undefined
getPositiveInteger('1') // undefined
getPositiveInteger(1) // 1
getPositiveInteger(-1) // undefined

Object (general)

const getObject = (value: unknown): object | undefined
getObject('foo')) // undefined
getObject({ foo: 'bar' }) // { foo: "bar" }
You might also like...

An interactive list of plugins for hex-rays' IDA Pro

Interactive IDA Plugin List This is a comprehensive list of plugins for IDA Pro that is more interactive, that is, it can be sorted and filtered to he

Dec 26, 2022

Label your form input like a boss with beautiful animation and without taking up space

#Label Better by Pete R. Label your form input like a boss with beautiful animation and without taking up space Created by Pete R., Founder of BucketL

Feb 5, 2022

A work-in-progress HTML sanitizer that strives for: performance like window.Sanitizer, readiness like DOMPurify, and ability to run in a WebWorker like neither of those.

Amuchina A work-in-progress HTML sanitizer that strives for: performance like window.Sanitizer, readiness like DOMPurify, and ability to run in a WebW

Sep 17, 2022

JSON Visio is data visualization tool for your json data which seamlessly illustrates your data on graphs without having to restructure anything, paste directly or import file.

JSON Visio is data visualization tool for your json data which seamlessly illustrates your data on graphs without having to restructure anything, paste directly or import file.

JSON Visio is data visualization tool for your json data which seamlessly illustrates your data on graphs without having to restructure anything, paste directly or import file.

Jan 4, 2023

A robust form library for Lit that enriches input components with easy-to-use data validation features.

A robust form library for Lit that enriches input components with easy-to-use data validation features.

EliteForms A robust form library for Lit that enriches input components with easy-to-use data validation features. Installation npm install elite-form

Jun 28, 2022

A table component for your Mantine data-rich applications, supporting asynchronous data loading, column sorting, custom cell data rendering, row context menus, dark theme, and more.

A table component for your Mantine data-rich applications, supporting asynchronous data loading, column sorting, custom cell data rendering, row context menus, dark theme, and more.

Mantine DataTable A "dark-theme aware" table component for your Mantine UI data-rich applications, featuring asynchronous data loading support, pagina

Jan 4, 2023

A plugin for Obsidian that can create input fields inside your notes and bind them to metadata fields.

Obsidian Meta Bind Plugin This plugin can create input fields inside your notes and bind them to metadata fields. New docs I am currently working on n

Jan 4, 2023

It shows an effective way to correct bus arrival information using data analytics based on Amazon Serverless such as Kiness Data Stream, Kinesis Data Firehose, S3, and Lambda.

It shows an effective way to correct bus arrival information using data analytics based on Amazon Serverless such as Kiness Data Stream, Kinesis Data Firehose, S3, and Lambda.

Amazon Serverless를 이용한 실시간 버스 정보 수집 및 저장 본 github repository는 버스 정보를 주기적으로 수집하여 분석할 수 있도록, Amazon Serverless인 Amazon Kinesis Data Stream, Kinesis Data

Nov 13, 2022
Comments
  • build(deps): bump minimist from 1.2.5 to 1.2.6

    build(deps): bump minimist from 1.2.5 to 1.2.6

    Bumps minimist from 1.2.5 to 1.2.6.

    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 0
Releases(v1.1.2)
Owner
Horatiu Vlad
Passionate JS architect & dev. Combining realism with perfectionism in order to achieve the ultimate simplicity, clarity and function.
Horatiu Vlad
Task manager Pro 📅 Use local storage to save data 💻

?? Task Manager Pro ?? Introducing different sections of the website : ⚙️ Setting section To change the color theme ?? Calendar section ??️ Task Manag

Negin Soleimani 9 Nov 14, 2022
Master Collection NFT. Mints NFTs on Ethereum containing unique combination of titles for fun.

Master NFT Collection Master NFT Collection is an NFT minting platform that mints NFTs that contain a unique combination of snazzy titles just for fun

MJ LEE 2 Mar 22, 2022
A plugin for Master Styles to group up styles and add selectors.

master-styles-group A plugin for Master Styles to group up styles and add selectors. THIS PROJECT IS IN BETA This project may contain bugs and have no

SerKo 5 Sep 27, 2022
"Pizza Party!" - A Jovo V4 master template supporting a lot of features

"Pizza Party!" - Yet another Jovo V4 master template supporting a lot of features There are a lot of Jovo examples around but I did not find any proje

Frank Börncke 8 Aug 2, 2022
FrontEnd Master algorithms!

next-course-starter A NextJS starter to get you started creating educational materials using Markdown Get Started Set up Node.js v14+ Clone this repo

ThePrimeagen 112 Dec 18, 2022
Compile Master CSS ahead of time with zero-configuration integration with build tools

CSS Compiler Compile Master CSS ahead of time with zero-configuration integration with build tools On this page Usage webpack.config.js vite.config.js

Master 5 Oct 31, 2022
A Bootstrap plugin to create input spinner elements for number input

bootstrap-input-spinner A Bootstrap / jQuery plugin to create input spinner elements for number input. Demo page with examples Examples with floating-

Stefan Haack 220 Nov 7, 2022
A phone input component that uses intl-tel-input for Laravel Filament

Filament Phone Input This package provides a phone input component for Laravel Filament. It uses International Telephone Input to provide a dropdown o

Yusuf Kaya 24 Nov 29, 2022
Github Repository for the resources shown in my 8 JavaScript Pro Tips Tutorial in Youtube

Part 1 - JavaScript Pro Tips - Learn with Sumit Table of Contents How to run Contact How to run Different lessons taught in the Youtube Tutorial are o

Learn with Sumit 28 Dec 28, 2022
FingerprintJS Pro Wrapper for React Single Page Applications (SPA)

FingerprintJS Pro React FingerprintJS Pro React is an easy-to-use React library for FingerprintJS Pro. This package works with FingerprintJS Pro, it i

FingerprintJS 29 Dec 15, 2022