Commit 9216aac7 authored by K2856's avatar K2856
Browse files

Rest API alku

parent ba843871
{
"CurrentProjectSetting": null
}
\ No newline at end of file
File added
......@@ -66,3 +66,26 @@ This section has moved here: https://facebook.github.io/create-react-app/docs/de
### `npm run build` fails to minify
This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify
###
Added few routes that should work. Made search, add, delete and modify to images/products and identifiers to what tuser and product should have.
Added files
Image_things
-listimg.js
-uploadimg.js
User
-index.ejs
User_things
product.js
user.js
routes
-image.js
-index.js
-user.js
###
Minä Niko Tallila tein niin paljon kun kerkesin tähän projektiin tähän vaiheeseen työt ja muut menot hidastivat ja vähensivät tekoa koronan lisäksi..
Tein noin 30-40h tähän osaani eli API perus himmeli koodia perus idea oli helppoa käsittää ja tehdä. Tämä ei ole ikinä ollut vahvinta osaamistani sekä se, että ei ollut "kunnon" kouluympäristöä tekemiseen vaikeutti omaa tekemistä.
Tekemällä oppii
\ No newline at end of file
const express = require("express"),
router = express.Router(),
passport = require("passport"),
request = require("request"),
Fuse = require("fuse.js"),
User = require("../models/user");
// Haku
let query;
let productData;
let options = {
shouldSort: true,
threshold: 0.3,
location: 0,
distance: 100,
maxPatternLength: 32,
minMatchCharLength: 1,
keys: [
"type",
"name",
"price",
"info"
]
};
router.get("/", (req, res) => {
if (!productData) { res.redirect("back") }
// Get all images/products from DB
Product.find({}, (err, allProducts) => {
if (err)
console.log(err)
else {
let fuse = new Fuse(allProducts, options);
let foundProducts = fuse.search(query);
res.render("search", { productData: productData, productData: foundProducts, query: query });
}
})
})
module.exports = router;
\ No newline at end of file
class ImageUpload extends Component {
constructor(props) {
super(props);
this.state = {
file: '',
imagePreviewUrl: ''
};
this._handleImageChange = this._handleImageChange.bind(this);
this._handleSubmit = this._handleSubmit.bind(this);
}
_handleSubmit(e) {
e.preventDefault();
// do something with -> this.state.file
}
_handleImageChange(e) {
e.preventDefault();
let reader = new FileReader();
let file = e.target.files[0];
reader.onloadend = () => {
this.setState({
file: file,
imagePreviewUrl: reader.result
});
}
reader.readAsDataURL(file)
}
render() {
let {imagePreviewUrl} = this.state;
let $imagePreview = null;
if (imagePreviewUrl) {
$imagePreview = (<img src={imagePreviewUrl} />);
}
return (
<div>
<form onSubmit={this._handleSubmit}>
<input type="file" onChange={this._handleImageChange} />
<button type="submit" onClick={this._handleSubmit}>Upload Image</button>
</form>
{$imagePreview}
</div>
)
}
// enables preview to imgs
}
\ No newline at end of file
<div class="container">
<div id="profilePic"><img src="<%= currentUser.profilePic %>"></div>
<div id="profileInfo">
<h2 class="display-3"><%= currentUser.username %></h2>
<p><%= currentUser.firstName %></p>
<p><%= currentUser.lastName %></p>
<p><%= currentUser.email %></p>
</div>
//display user info
<form class="edit-form" action="/user/<%= currentUser._id %>/?_method=DELETE" method="post">
<button class="btn btn-danger">Edit account</button>
</form>
<form class="delete-form" action="/user/<%= currentUser._id %>/?_method=DELETE" method="post">
<button class="btn btn-danger">Delete account</button>
</form>
// able to delete or edit
<div>
<h3>Suosikit</h3>
<div class="card-columns">
<% itemData.forEach(item => { %>
<div class="card thumbnail">
<a href="/items/<%= item._id %>">
<img src="<%= item.image %>" alt="kuva">
</a>
</div>
</div>
\ No newline at end of file
const mongoose = require("mongoose");
// Schema asetukset
const placeSchema = new mongoose.Schema({
type: String,
name: String,
image: String,
description: String,
});
module.exports = mongoose.model("Product", placeSchema);
\ No newline at end of file
const userSchema = new mongoose.Schema({
username: String,
password: String,
firstName: String,
lastName: String,
email: String,
favorites: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Event"
}
],
isAdmin: Boolean,
});
\ No newline at end of file
onst express = require("express");
const router = express.Router();
const Event = require("../models/images");
const User = require("../models/user");
const middleware = require("../middleware");
// Index - nyt kaikki kuvat/tuotteet
router.get("/", (req, res) => {
// Get all images/products from DB
Event.find({}, (err, allImages) => {
if (err)
console.log(err)
else
res.render("products/index", { products: allProducts });
})
})
// Create - luo tuote
router.post("/", middleware.isLoggedIn, (req, res) => {
// Hae lomakedata
let name = req.body.name;
let image = req.body.image;
let desc = req.body.description;
let author = {
id: req.user._id,
username: req.user.username
}
let newProduct = { name: name, image: image, description: desc, author: author };
// Lis ja tallenna tapahtuma databaseen
Product.create(newProduct, (err, newlyCreated) => {
if (err)
console.log(err);
else
// Ohjaa tuotteen sivulle
console.log(newlyCreated);
res.redirect("/products/" + newlyCreated._id);
});
})
// NEW - lomake tuotteen luontiin
router.get("/new", middleware.isLoggedIn, (req, res) => {
res.render("products/new");
})
// SHOW - nyt tuotteen tiedot
router.get("/:id", (req, res) => {
// Etsi tuote ID:n avulla
Product.findById(req.params.id, (err, foundEvent) => {
if (err)
console.log(err)
else
res.render("products/show", { event: foundEvent });
})
})
// EDIT - muokkaa tuotetta
router.get("/:id/edit", middleware.checkEventOwner, (req, res) => {
Product.findById(req.params.id, (err, foundEvent) => {
res.render("products/edit", { event: foundEvent });
});
});
// UPDATE tallenna muutokset databaseen
router.put("/:id", middleware.checkEventOwner, (req, res) => {
// find and update the correct event
// redirect show page
Product.findByIdAndUpdate(req.params.id, req.body.event, (err, updatedEvent) => {
if (err) {
console.log(err)
res.redirect("/products");
} else {
res.redirect("/products/" + req.params.id);
}
})
})
// DESTROY poista tuote
router.delete("/:id", middleware.checkEventOwner, (req, res) => {
Event.findByIdAndRemove(req.params.id, (err) => {
if (err) {
res.redirect("/products");
} else
res.redirect("/products");
})
})
module.exports = router;
const express = require("express"),
router = express.Router(),
passport = require("passport"),
User = require("../models/user"),
request = require("request"),
middleware = require("../middleware");
// Root Route
router.get("/", (req, res) => {
res.render("index");
});
// Rekisterinti
router.post("/register", (req, res) => {
let newUser = new User(
{
username: req.body.username,
firstName: req.body.firstName,
lastName: req.body.lastName,
email: req.body.email,
});
User.register(newUser, req.body.password, (err, user) => {
if (err) {
req.flash("error", "Kyttjnimi ei ole vapaana. Kokeile toista nime.");
return res.redirect("back");
}
req.flash("success", "Tervetuloa " + newUser.username);
passport.authenticate("local")(req, res, () => {
res.redirect("back");
})
});
});
// Kirjautuminen
router.post("/login", passport.authenticate("local",
{
successRedirect: "back",
successFlash: 'Tervetuloa!',
failureRedirect: "back",
failureFlash: "Vr kyttjnimi tai salasana"
}
));
// Uloskirjautuminen
router.get("/logout", (req, res) => {
req.logout();
req.flash("success", "Kirjauduttu Ulos");
res.redirect("/");
})
// Listaa kaikki kyttjt esim. vain admin jos tukos tapahtuisi
router.get("/users", middleware.isLoggedIn, (req, res) => {
// Hae kaikki kyttjt
User.find({}, (err, allUsers) => {
if (err) {
console.log(err)
res.redirect("back");
}
else {
res.render("user/list", { user: allUsers });
}
})
})
module.exports = router;
\ No newline at end of file
const express = require("express");
const router = express.Router();
const User = require("../models/user");
const middleware = require("../middleware");
router.get("/", middleware.isLoggedIn, (req, res) => {
// Hae Suosikit
User.findById(req.user._id).populate("favorites").exec((err, user) => {
if (err) {
console.log(err);
res.redirect("back");
} else {
//console.log(user.favorites)
res.render("user/index", { eventData: user.favorites });
}
})
})
// Lis suosikkeihin
router.get("/:id", middleware.isLoggedIn, (req, res) => {
User.findById(req.user._id, (err, user) => {
if (err) {
console.log(err);
res.redirect("/back");
} else {
user.favorites.push(req.params.id);
console.log(user)
user.save();
req.flash("success", "Listty Suosikkeihin!")
res.redirect("/user");
}
})
})
// DESTROY poista tili
router.delete("/:id", middleware.isLoggedIn, (req, res) => {
User.findByIdAndRemove(req.params.id, (err) => {
if (err) {
req.flash("error", "Tilinpoisto epionnistui");
res.redirect("back");
} else
req.flash("success", "Kyttjtili poistettu");
res.redirect("back");
})
})
module.exports = router;
\ 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