Skip to content

Javascript JSON model as same as JSONModel or ObjectMapper in iOS. JSON object mapping in JS.

License

Notifications You must be signed in to change notification settings

vikrampunchh/react-native-jsmodel

 
 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

10 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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);
    }
}
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

  • Basic model
  • Object Cloning
  • keyMapper
  • toJSON converted all data as JSON string
  • Array parsing can possible as json.arr.map(i => new ExtendsFromJSModel(i));
  • Object parsing as new ExtendsFromJSModel(json)
  • 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>') @ er.gauravds@gmail.com.

❤️ Voila! Happy coding...

About

Javascript JSON model as same as JSONModel or ObjectMapper in iOS. JSON object mapping in JS.

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Objective-C 39.6%
  • JavaScript 33.0%
  • Python 15.5%
  • Java 11.9%