Commit 393f4c64 by mukesh

worked on react

parent ebb60b88
class Api::V1::HotelsController < ApplicationController
def index
hotel = Hotel.all.order(created_at: :desc)
render json: hotel
end
def create
hotel = Hotel.create!(hotel_params)
if hotel
render json: hotel
else
render json: hotel.errors
end
end
def show
if hotel
render json: hotel
else
render json: hotel.errors
end
end
def destroy
hotel&.destroy
render json: { message: 'Hotel deleted!' }
end
private
def hotel_params
params.permit(:name, :description)
end
def hotel
@hotel ||= Hotel.find(params[:id])
end
end
import React from "react";
import { Link } from "react-router-dom";
class Hotel extends React.Component {
constructor(props) {
super(props);
this.state = { hotel: { description: "" } };
this.addHtmlEntities = this.addHtmlEntities.bind(this);
this.deleteHotel = this.deleteHotel.bind(this);
}
componentDidMount() {
const {
match: {
params: { id }
}
} = this.props;
const url = `/api/v1/hotels/show/${id}`;
fetch(url)
.then(response => {
if (response.ok) {
return response.json();
}
throw new Error("Network response was not ok.");
})
.then(response => this.setState({ hotel: response }))
.catch(() => this.props.history.push("/hotels"));
}
addHtmlEntities(str) {
return String(str)
.replace(/&lt;/g, "<")
.replace(/&gt;/g, ">");
}
deleteHotel() {
const {
match: {
params: { id }
}
} = this.props;
const url = `/api/v1/hotels/destroy/${id}`;
const token = document.querySelector('meta[name="csrf-token"]').content;
fetch(url, {
method: "DELETE",
headers: {
"X-CSRF-Token": token,
"Content-Type": "application/json"
}
})
.then(response => {
if (response.ok) {
return response.json();
}
throw new Error("Network response was not ok.");
})
.then(() => this.props.history.push("/hotels"))
.catch(error => console.log(error.message));
}
render() {
const { hotel } = this.state;
let descriptionList = "No description available";
if (hotel.description.length > 0) {
descriptionList = hotel.description
.split(",")
.map((description, index) => (
<li key={index} className="list-group-item">
{description}
</li>
));
}
return (
<div className="">
<div className="hero position-relative d-flex align-items-center justify-content-center">
<div className="overlay bg-dark position-absolute" />
<h1 className="display-4 position-relative text-white">
{hotel.name}
</h1>
</div>
<div className="container py-5">
<div className="row">
<div className="col-sm-12 col-lg-3">
<ul className="list-group">
<h5 className="mb-2">Description List</h5>
{descriptionList}
</ul>
</div>
<div className="col-sm-12 col-lg-2">
<button type="button" className="btn btn-danger" onClick={this.deleteHotel}>
Delete hotel
</button>
</div>
</div>
<Link to="/hotels" className="btn btn-link">
Back to hotels
</Link>
</div>
</div>
);
}
}
export default Hotel;
\ No newline at end of file
import React, { Component } from 'react';
import { Link } from "react-router-dom";
class Hotels extends React.Component {
constructor(props) {
super(props);
this.state = {
hotels: []
};
}
componentDidMount() {
const url = "/api/v1/hotels/index";
fetch(url)
.then(response => {
if (response.ok) {
return response.json();
}
throw new Error("Network response was not ok.");
})
.then(response => this.setState({ hotels: response }))
.catch(() => this.props.history.push("/"));
}
render() {
const { hotels } = this.state;
const allHotels = hotels.map((hotel, index) => (
<div key={index} className="col-md-6 col-lg-4">
<div className="card mb-4">
<div className="card-body">
<h5 className="card-title">{hotel.name}</h5>
<Link to={`/hotel/${hotel.id}`} className="btn custom-button">
View Hotel
</Link>
</div>
</div>
</div>
));
const noHotel = (
<div className="vw-100 vh-50 d-flex align-items-center justify-content-center">
<h4>
No hotels yet. Why not <Link to="/new_hotel">create one</Link>
</h4>
</div>
);
return (
<>
<section className="jumbotron jumbotron-fluid text-center">
<div className="container py-5">
<h1 className="display-4">Hotels for every occasion</h1>
<p className="lead text-muted">
We’ve pulled together our most popular hotels, our latest
additions, and our editor’s picks, so there’s sure to be something
tempting for you to try.
</p>
</div>
</section>
<div className="py-5">
<main className="container">
<div className="text-right mb-3">
<Link to="/hotel" className="btn custom-button">
Create New Hotel
</Link>
</div>
<div className="row">
{hotels.length > 0 ? allHotels : noHotel}
</div>
<Link to="/" className="btn btn-link">
Home
</Link>
</main>
</div>
</>
);
}
}
export default Hotels;
\ No newline at end of file
import React from "react";
import { Link } from "react-router-dom";
class NewHotel extends React.Component {
constructor(props) {
super(props);
this.state = {
name: "",
description: ""
};
this.onChange = this.onChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.stripHtmlEntities = this.stripHtmlEntities.bind(this);
}
stripHtmlEntities(str) {
return String(str)
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;");
}
onChange(event) {
this.setState({ [event.target.name]: event.target.value });
}
onSubmit(event) {
event.preventDefault();
const url = "/api/v1/hotels/create";
const { name, description } = this.state;
if (name.length == 0 || description.length == 0 )
return;
const body = {
name,
description,
};
const token = document.querySelector('meta[name="csrf-token"]').content;
fetch(url, {
method: "POST",
headers: {
"X-CSRF-Token": token,
"Content-Type": "application/json"
},
body: JSON.stringify(body)
})
.then(response => {
if (response.ok) {
return response.json();
}
throw new Error("Network response was not ok.");
})
.then(response => this.props.history.push(`/hotel/${response.id}`))
.catch(error => console.log(error.message));
}
render() {
return (
<div className="container mt-5">
<div className="row">
<div className="col-sm-12 col-lg-6 offset-lg-3">
<h1 className="font-weight-normal mb-5">
Add a new hotel to our awesome collection.
</h1>
<form onSubmit={this.onSubmit}>
<div className="form-group">
<label htmlFor="name">Name</label>
<input
type="text"
name="name"
id="name"
className="form-control"
required
onChange={this.onChange}
/>
</div>
<div className="form-group">
<label htmlFor="Description">Description</label>
<input
type="text"
name="description"
id="hotelDescription"
className="form-control"
required
onChange={this.onChange}
/>
<small id="descriptionHelp" className="form-text text-muted">
Separate each description with a comma.
</small>
</div>
<button type="submit" className="btn custom-button mt-3">
Create Hotel
</button>
<Link to="/hotels" className="btn btn-link mt-3">
Back to hotels
</Link>
</form>
</div>
</div>
</div>
);
}
}
export default NewHotel;
\ No newline at end of file
......@@ -7,6 +7,9 @@ import NewRecipe from "../components/NewRecipe";
import Employees from "../components/Employees";
import Employee from "../components/Employee";
import NewEmployee from "../components/NewEmployee";
import Hotels from "../components/hotel/Hotels";
import Hotel from "../components/hotel/Hotel";
import NewHotel from "../components/hotel/NewHotel";
export default (
<Router>
......@@ -18,6 +21,9 @@ export default (
<Route path="/employees" exact component={Employees} />
<Route path="/employee/:id" exact component={Employee} />
<Route path="/employee" exact component={NewEmployee} />
<Route path="/hotels" exact component={Hotels} />
<Route path="/hotel/:id" exact component={Hotel} />
<Route path="/hotel" exact component={NewHotel} />
</Switch>
</Router>
);
\ No newline at end of file
class Hotel < ApplicationRecord
validates :name, presence: true
validates :description, presence: true
end
Rails.application.routes.draw do
namespace :api do
namespace :v1 do
get 'hotels/index'
post 'hotels/create'
get 'hotels/show/:id', to: 'hotels#show'
delete 'hotels/destroy/:id', to: 'hotels#destroy'
end
end
namespace :api do
namespace :v1 do
get 'employees/index'
post 'employees/create'
get 'employee/show/:id', to: 'employees#show'
......
class CreateHotels < ActiveRecord::Migration[5.2]
def change
create_table :hotels do |t|
t.string :name, null: false
t.text :description, null: false
t.timestamps
end
end
end
......@@ -10,11 +10,24 @@
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema.define(version: 2020_09_30_024252) do
ActiveRecord::Schema.define(version: 2020_10_03_050459) do
# These are extensions that must be enabled in order to support this database
enable_extension "plpgsql"
create_table "designationns", force: :cascade do |t|
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "designations", force: :cascade do |t|
t.string "name"
t.string "designation"
t.string "description"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "employees", force: :cascade do |t|
t.string "firstName", null: false
t.string "lastName", null: false
......@@ -27,6 +40,21 @@ ActiveRecord::Schema.define(version: 2020_09_30_024252) do
t.datetime "updated_at", null: false
end
create_table "hotels", force: :cascade do |t|
t.string "name", null: false
t.text "description", null: false
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "humen", force: :cascade do |t|
t.string "name"
t.text "designation"
t.text "instruction"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "recipes", force: :cascade do |t|
t.string "name", null: false
t.text "ingredients", null: false
......
......@@ -21,4 +21,9 @@
address: "Noida, UP",
dob: "11/11/1111"
)
Hotel.create(
name: "Hotel #{i + 1}",
description: '227g tub clotted cream, 25g butter, 1 tsp cornflour,100g parmesan, grated nutmeg, 250g fresh fettuccine or tagliatelle, snipped chives or chopped parsley to serve (optional)',
)
end
\ No newline at end of file
FactoryBot.define do
factory :hotel do
name { 'Jaypee' }
description {'Great hotel'}
end
factory :random_hotel, class: Hotel do
name { Faker::Name.name }
description { Faker::Name.description }
end
end
require 'rails_helper'
RSpec.describe Hotel, type: :model do
puts 'tests file for hotel run'
context 'Validation Test Case' do
let(:hotel) { build(:hotel) }
it 'hotelName validation' do
# hotel = Hotel.new(name: 'jaypee', description: 'Great place')
hotel.hotelName = nil
expect(hotel.save).to eq(false)
end
it 'description validation' do
#hotel = hotel.new(hotelName: 'Quality', description: 'Tests quality of product at different stages')
hotel.description = nil;
expect(hotel.save).to eq(false)
end
it 'null validation' do
hotel = hotel.new(hotelName: 'Quality', description: 'Tests quality of product at different stages').save
expect(hotel).to eq(true)
end
end
context 'hotel Table Operations Test Case' do
it 'Save Data Test' do
hotel = hotel.new(hotelName: 'Gulati', description: 'Tests quality of product at different stages').save
expect(hotel).to eq(true)
end
end
#pending "add some examples to (or delete) #{__FILE__}"
end
pending "add some examples to (or delete) #{__FILE__}"
end
require 'rails_helper'
\ No newline at end of file
require 'rails_helper'
RSpec.describe "Api::V1::Hotels", type: :request do
describe "GET /index" do
it "returns http success" do
get "/api/v1/hotels/index"
expect(response).to have_http_status(:success)
end
end
describe "GET /create" do
it "returns http success" do
get "/api/v1/hotels/create"
expect(response).to have_http_status(:success)
end
end
describe "GET /show" do
it "returns http success" do
get "/api/v1/hotels/show"
expect(response).to have_http_status(:success)
end
end
describe "GET /destroy" do
it "returns http success" do
get "/api/v1/hotels/destroy"
expect(response).to have_http_status(:success)
end
end
end
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment