User:Testafonline/sandbox

NODE============================================= app.js

var express   =    require('express'); var bodyparser   =    require('body-parser'); var Cors   =    require('cors'); var router   =    express.Router; var Routes   = require('./Routes');

var app   =    express;

app.use(bodyparser.urlencoded({extend:true})); app.use(bodyparser.json); app.use(Cors); app.use('/',Routes);

app.listen('8089', '127.0.0.1', function (err) {   if(err){        console.log(err);        process.exit(-2);    }    console.log('Server listen: 8089 port'); });

Routes.js

var Express = require('express'); var userroute = require('./User/User.route'); var itemroute = require('./Items/Item.route'); var Routes = Express.Router;

Routes.use('/user/', userroute); Routes.use('/item/', itemroute);

module.exports = Routes;

DBSchema.js

const mongoose = require('mongoose'); const Schema = mongoose.Schema;

const UserSchema =new Schema({   name:{        type:String,        require:true    },    address:{        type:String,        require:true    },    gender:{        type:String,        require:true    } });

const ItemSchema = new Schema({   Iname:{        type:String,        require:true    },    IWeight:{        type:String,        require:true    } });

mongoose.model('UserSchema', UserSchema); mongoose.model('ItemSchema', ItemSchema);

mongoose.connect('mongodb://localhost:27017/User_AF_Final',function (err) {   if(err){        console.log(err);            process.exit(-1);    }

console.log('Connected to the DB'); });

module.exports = mongoose;

In User Directory-- User.controller.js

var mongoose = require('../DBSchema') var userSchema = mongoose.model('UserSchema'); var controller = function { this.add = function (userInstance) { return new Promise(function (resolve, reject) {           var user = new userSchema({ name:userInstance.name, address:userInstance.address, gender:userInstance.gender })           user.save.then(function  { resolve({'status':200,'message':'User added'}); }).catch(function (err) { reject({'status':500, 'message':'error - '+err}); })       });    }

this.getAll = function { return new Promise(function (resolve, reject) {           userSchema.find.exec.then(function (data) { resolve({'status':200, 'message':'User found', 'data':data}); }).catch(function (err) { reject({'status':404, 'message':'error - '+err}); })       });    }    this.getOne = function (id) { return new Promise(function (resolve, reject) {           userSchema.find({_id:id}).exec.then(function (data) { resolve({'status':200, 'message':'User found', 'data':data}); }).catch(function (err) { reject({'status':404, 'message':'error - '+err}); })       });    }    this.deleteUser = function (id) { return new Promise(function (resolve, reject) {           userSchema.remove({name:id}).then(function  { resolve({'status':200, 'message':'Successfully deleted'}); }).catch(function (err) { reject({'status':500, 'message':'error - '+err}); });       });    }    this.updateUser = function (id, newdata) { return new Promise(function (resolve, reject) {           userSchema.update({_id:id},newdata).then(function  { resolve({'status':200, 'message':'Updated'}); }).catch(function (err) { reject({'status':500, 'message':'error - '+err}); });       });    } }

module.exports = new controller;

In User directory-- User.routes.js

var express    = require('express'); var router     = express.Router; var controller	= require('./User.controller');

router.post('/', (req, res) => {   controller.add(req.body).then(response => { res.status(response.status).send(response.message); }).catch(err => { res.status(err.status).send(err.message); }) });

router.get('/', (req, res) => {   controller.getAll.then(response => { res.status(response.status).send(response); }).catch(err => { res.status(err.status).send(err.message); }) });

router.get('/:id', (req, res) => {   controller.getOne(req.params.id).then(response => { res.status(response.status).send(response); }).catch(err => { res.status(err.status).send(err.message); }) });

router.put('/:id', (req, res) => {   controller.updateUser(req.params.id, req.body).then(response => { res.status(response.status).send(response); }).catch(err => { res.status(err.status).send(err.message); }) });

router.delete('/:id', (req, res) => {   controller.deleteUser(req.params.id).then(response => { res.status(response.status).send(response); }).catch(err => { res.status(err.status).send(err.message); }) })

module.exports = router;

React.js========================================================

app.js

import React, { Component } from 'react'; import logo from './logo.svg'; import './App.css'; import AddUser from './AddUser';

class App extends Component { render { return (     add a div tag and the AddUser here    ); } }

export default App;

AddUser.js

import React, {Component} from 'react'; import axios from 'axios'; import Base from './Static.common'; import ViewUsers from './ViewUsers';

export default class AddUser extends Component{

constructor(props) { super(props); this.state = { arr: [], };   }

addnewUser(event){ event.preventDefault;

if(!this.refs.username.value || !this.refs.address.value || !this.refs.gender.value){ alert('Error'); }       else{ axios.post(Base.API+'/user/',{name:this.refs.username.value,           address:this.refs.address.value,            gender:this.refs.gender.value}).then(function (result) {                if(result.status === 200){                    alert('User Added to the System');                }            }).catch(function (err) {                alert('Error - '+err);            }); }   }

render{ return(           div className={'addUser'} align="center"                header                    h2 Add User details /h2                /header                p Fill the form /p

form onSubmit={this.addnewUser.bind(this)} table tbody tr tag open.inside the tr tag open two td tags.inside those create label and input field.give rf to identify. for dropdown menu open td tag in tr tags and create select tag slect ref={'gender'} option value={'Male'} Male /option /select /tbody /table

div button type={'submit'}>Register /button ViewUsers/ /div /form

/div );   } }

Static.common.js

var CommonDetails = function { this.APInode = 'http://localhost:8089'; this.API = 'http://localhost:8081'; }

module.exports = new CommonDetails;

ViewUser.js

import React, {Component} from 'react'; import axios from 'axios'; import Base from './Static.common'; import propTypes from 'prop-types' import AddUser from './AddUser'

export default class ViewUsers extends Component{

constructor(props){

super(props);

this.state = { userlist : [], };

}

static get propTypes{ return{ userlist:propTypes.array, fetchall:propTypes.func }   }

fetchall(event){ event.preventDefault; let test = this; axios.get(Base.API+'/user/').then(function (result) {

if(result.status === 200){ test.setState({                   userlist:result.data.data || result.data                }); }       }).catch(function (err) { alert('Error - '+ err) });   }

deleteuser(event){

event.preventDefault; axios.delete(Base.APInode+'/user/'+this.refs.deletename.value).then(function (result) {           if(result.status === 200){                alert('Done');

}       }).catch(function (err) { alert('Eroor - '+err); });   }

render{ return(                   View All                                            Delete User                 table                    thead                    tr                        th Name /th                        th Address /th                        th Gender /th                    /tr                    /thead                    tbody                    {                        this.state.userlist.map(function (Userlist) { return(tr key={Userlist.name}>                               td {Userlist.name} /td                                td {Userlist.address} /td                                td {Userlist.gender} /td                            /tr); })                   }

);   } }

SPRING============================================================

User.java

package com.affinal.finalexam.User;

import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.data.annotation.Id;

@Document(collection = "userschemas") public class User {

@Id String Id; String name; String address; String gender; public User(String Id,String name, String address,String gender) { this.Id = Id; this.name = name; this.address = address; this.gender = gender; }

public String getId { return Id; }

public void setId(String id) { Id = id; }

public String getName { return name; }

public void setName(String name) { this.name = name; }

public String getAddress { return address; }

public void setAddress(String address) { this.address = address; }

public String getGender { return gender; }

public void setGender(String gender) { this.gender = gender; }

}

UserRepository.java (Interface)

package com.affinal.finalexam.repository;

import org.bson.types.ObjectId; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.stereotype.Repository;

import com.affinal.finalexam.User.User;

@Repository public interface UserREpository extends MongoRepository { }

Usercontroller.java

package com.affinal.finalexam.controller;

import java.util.List; import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;

import com.affinal.finalexam.User.User; import com.affinal.finalexam.repository.UserREpository;

@RequestMapping("/user") @RestController public class UserController {

@Autowired private UserREpository repo; @CrossOrigin @PostMapping(value="/") public String saveUser(@RequestBody User user) { repo.save(user); return "Added usser with Name: "+user.getName; }	@CrossOrigin @GetMapping(value="/") public List getusers{ return repo.findAll; }	@CrossOrigin @GetMapping(value="/{id}") public Optional getUser(@PathVariable String id){ System.out.println(id); return repo.findById(id); }	@CrossOrigin @DeleteMapping(value="/{id}") public String deleteUser(@PathVariable String id) { repo.deleteById(id); return "Deleted user with id: "+id; } }

application.properties

spring.data.mongodb.host=localhost spring.data.mongdb.port=27017 spring.data.mongodb.database=User_AF_Final server.port=8081