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

react-native-jsmodel

v0.0.6

Published

JSON parse into JS model as same as JSONModel or object mapper in iOS.

Downloads

617

Readme

react-native-jsmodel: JSModel

version

Preface

Are you coming from iOS native development background, newbies to JavaScript & react-native. Thinking of model based approach for development, and missing JSONModel(Objective-C) and ObjectMapper(swift). This approach is quite same as them or even more better. No need to add more dynamic keys.

Features

  • No need to add keys in name.
  • No need to implement nested child unless until you would interested to implement some methods on that child element.
  • keyMapper to rename the field names.
  • ease to implement and use.

Installation

  • Run this command $ npm install react-native-jsmodel --save

Implementation

  • import in js file as import JSModel from 'react-native-jsmodel'; see example
import JSModel from 'react-native-jsmodel';

export default class MockModel extends JSModel {
	message() {
		return 'This message added by JSModel: ' + this.errorMessage;
	}
}
  • Make object of your model as const model = new MockModel(Mock); see example
import React from 'react';
import { AppRegistry, StyleSheet, Text, View } from 'react-native';
import MockModel from './MockModel';
import Mock from './Mock.json';

export default class TestJSModel extends React.Component {
	render() {
		const model = new MockModel(Mock);
		return (
			<View style={styles.container}>
				<Text style={styles.welcome}>
					{model.message()}
				</Text>
			</View>
		);
	}
}
const styles = StyleSheet.create({
	container: {
		flex: 1,
		justifyContent: 'center',
		alignItems: 'center',
		backgroundColor: '#F5FCFF'
	},
	welcome: {
		fontSize: 20,
		textAlign: 'center',
		margin: 10
	}
});

AppRegistry.registerComponent('TestJSModel', () => TestJSModel);
In detail:
  • Must inherit root object from JSModel. e.g. class Parent extends JSONModel.
  • Just inherit all models from JSModel that need to implement some methods, otherwise no need to create class. e.g. common & root is implemented but orignal is not implemented.
  • In parent model add child object as below.
constructor(json) {
    super(json);
    if (this.validate(json)) {
      this.common = eval('new Common(json.common)');
      this.root = new Root(json.root);
    }
}

Demo Code

const json = {
	name: 'Level 1',
	age: 12,
	common: {
		name: 'Level 2',
		age: 19,
		new_name: 'key name to change',
		update_key: 'update data'
	},
	orignal: {
		name: 'Orignal Name'
	},
	root: {
		rootKey: 'L2: rootValue'
	}
};

const modelObj = new Parent(json);
modelObj.print();
modelObj.common.show();
console.log(modelObj.common.name);
console.log(JSON.stringify(modelObj, null, 2));

Implementation by bare minimum changes using keyMapper

const json = {
	first_name: 'James',
	last_name: 'Bond'
};

export default class MockModel extends JSModel {
	constructor(json) {
		super(json);
		if (this.validate(json)) {
			this.keyMapper({ first_name: 'firstName', last_name: 'lastName' });
		}
	}

	name() {
		return this.firstName + ' ' + this.lastName;
	}
}

const modelObj = new MockModel(json);
console.log(modelObj.firstName); // James
console.log(modelObj.name()); // James Bond
console.log(modelObj.first_name); // undefined
console.log(modelObj.toJSON()); // {"first_name":"James","last_name":"Bond"}

To test this demo code run: $ npm i && npm start

Implementation (recommend)

const json = {
	first_name: 'James',
	last_name: 'Bond',
	address: [
		{
			name: 'home',
			lane: '22/A',
			street: 'Bake Street',
			landmark: 'Near Hey NY restaurant',
			city: 'London'
		},
		{
			name: 'office',
			lane: '3rd Floor',
			street: 'Eye HeadRoom',
			landmark: 'Near Denmark Hotel',
			city: 'London'
		}
	]
};

class AddressModel extends JSModel {
	constructor(json) {
		super();
		if (this.validate(json)) {
			this.name = json.name;
			this.lane = json.lane;
			this.street = json.street;
			this.landmark = json.landmark;
			this.city = json.city;
		}
	}

	isNames(k: string): boolean {
		return this.name == k;
	}
}

class UserModel extends JSModel {
	constructor(json) {
		super();
		if (this.validate(json)) {
			this.firstName = json.first_name;
			this.lastName = json.last_name;
			this.address = json.address.map(i => new AddressModel(i));
		}
	}

	name() {
		return this.firstName + ' ' + this.lastName;
	}

	findAddressByName(name: string = 'home'): Array {
		return this.address.filter(i => i.isNames(name));
	}
}

const user = new UserModel(json);
console.log(user.firstName); // James
console.log(user.name()); // James Bond
console.log(user.first_name); // undefined
console.log(user.toJSON()); // {"first_name":"James","last_name":"Bond"}
console.log(user.findAddressByName('home')); // {name: "home", lane: "22/A", street: "Bake Street", landmark: "Near Hey NY restaurant", city: "London"}

Checklist

  • [x] Basic model
  • [x] Object Cloning
  • [x] keyMapper
  • [x] toJSON converted all data as JSON string
  • [x] Array parsing can possible as json.arr.map(i => new ExtendsFromJSModel(i));
  • [x] Object parsing as new ExtendsFromJSModel(json)
  • [x] Example added
  • [ ] Advance Model with type check using prop-types
  • [ ] Test cases for model (jest/mocha/ ** or something better**)
  • [ ] travis-ci setup

Feedbacks

  • I love to hear your valuable feedbacks, suggestions & issues. Please raise a issue on the repo or email me (as subject: 'jsmodel#issue <topic>') @ [email protected].

❤️ Voila! Happy coding...