Commit 6606b01c authored by Hedda Mathilde Sæther Langvik's avatar Hedda Mathilde Sæther Langvik
Browse files

Merge branch 'backend' into 'master'

#13 basic setup database

See merge request !4
parents e9568381 2e954ac1
import Axios from "axios"
const API_URL = "http://it2810-10.idi.ntnu.no:3001/api/"
export function GetAllData() {
console.log("we're in")
fetch(API_URL + "getData")
.then((data) => data.json())
.then((res) => {
if(res.data){console.log("Should return data"); return res.data}
else{console.log("Empty")};
})
}
export const GetDataFromSearch = (search) => {
fetch(API_URL + "search/" + search)
.then((data) => data.json())
.then((res) => {return res.data})
}
export const GetDataFromId = (destinationID) => {
fetch(API_URL + "getDataFrom/" + destinationID)
.then((data) => data.json())
.then((res) => {return res.data})
}
export const UpdatePopulatiry = (destinationID, newPopularity) => {
Axios.post(API_URL + "updateData", {
id: destinationID,
update: { popularity: newPopularity },
})
}
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// this will be our data base's data structure
// vi må endre dette til hva vi skal ha i våre objekter
const DestinationSchema = new Schema(
{
id: Number,
name: String,
description: String,
continent: String,
country: String,
source: String,
img: String,
popularity: Number
},
{ timestamps: true }
);
// export the new Schema so we could modify it using Node.js
module.exports = mongoose.model("Destination", DestinationSchema, 'test');
const Destinations = require('../models/DestinationSchema');
const express = require('express');
const router = express.Router();
// this is our update method
// this method overwrites existing data in our database
router.post('/updateData', (req, res) => {
const { id, update } = req.body;
Destinations.findByIdAndUpdate(id, update, (err) => {
if (err) return res.json({ success: false, error: err });
return res.json({ success: true });
});
});
// this is our get method to get data by id for destination page
router.get('/getDataFrom/:id', (req, res, next) => {
var destinatoinID = req.params.id;
Destinations.findById(destinatoinID, (err, data) => {
if (err) return res.json({ success: false, error: err });
return res.json({ success: true, data: data });
});
});
// get all data
router.get('/getData', (req, res) => {
Destinations.find((err, data) => {
if (err) return res.json({ success: false, error: err });
else{
var sorted = this.sortData(data)
return res.json({ success: true, data: sorted });
}
});
});
//get the three most popular destinations to show at the main page
router.get('/threeMostPopular', (req, res) => {
Destinations.find().sort({popularity: -1}).limit(3).exec(function(err, data){
if (err) return res.json({ success: false, error: err });
return res.json({ success: true, data: data });
})
})
router.get('/search/:word', (req, res, next) => {
const word = req.params.word.toLowerCase()
Destinations.find({$or: [{'name': word}, {'country': word}, {'continent': word}]}, function (err, data){
if (err) return res.json({ success: false, error: err });
else{
var sorted = this.sortData(data)
return res.json({ success: true, data: sorted });
}
})})
router.get('/search/:continent/:word', (req, res) => {
const continent = req.params.continent.toLowerCase()
const word = req.params.word.toLowerCase()
Destinations.find({ $and: [ {$or: [{'name': word}, {'country': word}]}, {'continent': continent} ]} , function (err, data){
if (err) return res.json({ success: false, error: err })
else{
var sorted = this.sortData(data)
return res.json({ success: true, data: sorted });
}
})})
//get the three most popular destinations to show at the main page
router.get('/wordcloudPopularity', (req, res) => {
Destinations.find().select('name popularity -_id').exec(function(err, data){
if (err) return res.json({ success: false, error: err });
return res.json({ success: true, data: data });
})
})
sortData = (data) => {
const sorting = req.params.sort;
if(sorting === "A-Z"){
const sorted = data.sort((a,b) => (a.name > b.name) ? 1:-1)
return sorted
}
if(sorting === "Popularity"){
const sorted = data.sort((a,b) => (a.popularity > b.popularity) ? -1:1)
return sorted
}
return data;
}
// append /api for our http requests
app.use('/api', router);
\ No newline at end of file
const mongoose = require('mongoose');
const express = require('express');
var cors = require('cors');
const bodyParser = require('body-parser');
const logger = require('morgan');
const API_PORT = 3001;
const app = express();
app.use(cors());
// this is our MongoDB database
const dbRoute =
'mongodb://it2810-10.idi.ntnu.no:27017/admin';
//'mongodb://hedda:webdev2019@it2810-10.idi.ntnu.no:27017/project3';
// connects our back end code with the database
mongoose.connect(dbRoute, { useNewUrlParser: true });
let db = mongoose.connection;
db.once('open', () => console.log('connected to the database'));
// checks if connection with the database is successful
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
// made for logging and bodyParser, parses the request body to be a readable json format
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(logger('dev'));
// launch our backend into a port
app.listen(API_PORT, () => console.log(`LISTENING ON PORT ${API_PORT}`));
......@@ -24,4 +24,4 @@ const TabNavigator = createBottomTabNavigator(
showLabel : false,
}});
export default createAppContainer(TabNavigator);
\ No newline at end of file
export default createAppContainer(TabNavigator);
export const continentFilter = (continent) => {
return (dispatch, getState) => {
dispatch({
type: 'CONTINENT_FILTER', continent
})
}
};
\ No newline at end of file
export const showDestination = (destinationID) => {
return (dispatch, getState) => {
dispatch({
type: 'SHOW_DESTINATION',
destinationID
})
}
};
\ No newline at end of file
export const setLength = (length) => {
return (dispatch, getState) => {
dispatch({
type: 'GET_LENGTH',
length
})
}
};
\ No newline at end of file
export const changeSearchword = (word) => {
return (dispatch, getState) => {
dispatch({
type: 'CHANGE_SEARCHWORD', word,
})
}
};
\ No newline at end of file
export const setData = (data) => {
return (dispatch, getState) => {
dispatch({
type: 'SET_DATA', data
})
}
};
\ No newline at end of file
// functions that return redux actions
// sort by different types, ex. continent, facilities..
export const sortBy = (sortType) => {
return (dispatch, getState) => {
dispatch({
type: 'SORT_TYPE',
sortType
})
}
};
\ No newline at end of file
import React, { Component } from 'react';
import {GetAllData, GetDataFromSearch} from '../../backend/fetchers'
import {View, Text} from 'react-native';
class Test extends Component {
state = {
data: []
}
componentDidMount() {
this.getDataFromDb()
}
getDataFromDb = () => {
this.setState({data: GetAllData()})
}
state = { }
render() {
return (
<View>
<Text>{console.log(this.state.data, "\n tjohei")}</Text>
</View>
);
}
}
export default Test;
\ No newline at end of file
const initState = {
destinationID: ""
}
const destinationReducer = (state = initState, action) => {
switch(action.type) {
case 'SHOW_DESTINATION':
return{destinationID: action.destinationID}
default: return state;
};
}
export default destinationReducer
\ No newline at end of file
const initState = {
searchWord: '',
continent: ''
}
const filterReducer = (state = initState, action) => {
switch(action.type) {
case 'CHANGE_SEARCHWORD':
return {searchWord: action.word, continent: state.continent}
case 'CONTINENT_FILTER':
return {searchWord: state.searchWord, continent: action.continent}
default: return state
}
}
export default filterReducer
const initState = {
length: 0,
}
const lengthReducer = (state = initState, action) => {
switch(action.type) {
case 'GET_LENGTH':
return{length: action.length}
default: return state;
};
}
export default lengthReducer;
\ No newline at end of file
const initState = {
data: [],
}
const setDataReducer = (state = initState, action) => {
switch(action.type) {
case 'SET_DATA':
return{data: action.data}
default: return state;
};
}
export default setDataReducer;
\ No newline at end of file
Supports Markdown
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