npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@onehop/json-methods

v1.2.0

Published

A utility for adding methods to any JSON object. For example, deserializing a user object from your API and adding a `.isAdult()`. Whilst this library works great for validation, use cases extend far beyond that. It was built for `@onehop/js` to enable re

Downloads

338

Readme

json-methods

A utility for adding methods to any JSON object. For example, deserializing a user object from your API and adding a .isAdult(). Whilst this library works great for validation, use cases extend far beyond that. It was built for @onehop/js to enable regular objects to have utility methods that are context aware (like fetching a deployment's containers in Hop).

Installation

# With yarn
yarn add @onehop/json-methods

# With npm
npm install --save @onehop/json-methods

Basic Example

For something a little bit more in depth, but still simple, check out /examples/basic.ts

import {create} from '@onehop/json-methods';

interface User {
	id: string;
	email: string;
	age: number;
}

const Users = create<User>().methods({
	// Methods must be created with method function syntax,
	// rather than property arrow functions (so that `this` can be bound)
	isAdult() {
		return this.age >= 18;
	},
});

// json is the JSON object that we want to add methods to
const json = await getUserFromAPI();
const user = Users.from(json);

// Or, if you have a JSON string, we can parse it for you
const user = Users.parse(json);

// Safely access properties:
console.log(user.email);

// And call our methods
console.log('Can watch the movie?:', user.isAdult());

Validation / Schemas

json-methods supports third-party schemas out of the box. You can write your own, or use things like Zod, Yup or Joi. The precondition is that the schema object itself has a method with the signature parse(data: unknown): T Here's a basic example using Zod:

import {create} from '@onehop/json-methods';
import {z} from 'zod';

// This schema has a .parse method internally, so it will work
// with json-methods without any modification
const schema = z.object({
	age: z.number().min(0),
});

const Users = create(schema).methods({
	isAdult() {
		return this.age >= 18;
	},
});

// During this phase, the schema will be used to validate the passed object.
// If you do not pass a schema, then the raw data will be used, but you
// could run into runtime errors if you try to access properties that don't exist!
// For this reason, it's recommended to always pass a schema if you can
const user = Users.from(await getUserFromAPI());

console.log('Can watch the movie?:', user.isAdult());

Advanced TypeScript

For more advanced use cases, there's a type exported called Infer that will allow you to get the full type of your object with the methods added

import {create, Infer} from '@onehop/json-methods';

const Users = create<{age: number}>().methods({
	isAdult() {
		return this.age >= 18;
	},
});

// UserWithMethods is {age: number} & {isAdult(): boolean}
type UserWithMethods = Infer<typeof Users>;