Skip to content

Instantly share code, notes, and snippets.

@teerasej
Last active December 22, 2021 08:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save teerasej/4b66c2704f845bf07efd8763f0ba01c0 to your computer and use it in GitHub Desktop.
Save teerasej/4b66c2704f845bf07efd8763f0ba01c0 to your computer and use it in GitHub Desktop.
import express from 'express';
import mongoose from 'mongoose';
import UserModel from './schemas/user.js';
const app = express();
const port = 3000;
app.use(express.json());
main().catch(function(error){ console.log(error) });
async function main() {
await mongoose.connect('mongodb://localhost:27017/dating_app');
// Route URL, เมนูในร้าน
app.get('/', function (request, response) {
response.send('hello');
});
app.post('/users', async function(request, response){
console.log(request.body);
let doc;
try {
const newUser = new UserModel(request.body);
doc = await newUser.save();
} catch (error) {
response.status(500).json(error.message);
}
response.json(doc);
});
// /users/1234
// /users/training@nextflow.in.th
app.get('/users/:email', async function(request, response){
console.log(request.params.email);
const doc = await UserModel.findOne({ email: request.params.email, password });
if(doc) {
response.json(doc);
} else {
response.status(404).send('email not found')
}
});
// UPDATE method PATCH
app.patch('/users', async function(request, response) {
console.log(request.body)
await UserModel.updateOne(
{ email: request.body.email },
request.body
);
response.send('ok UPDATE');
});
app.delete('/users', async function(request, response){
console.log(request.body);
await UserModel.findByIdAndDelete(request.body.id);
response.send('ok DELETE');
});
app.post('/users/login', async function(request, response){
console.log(request.body);
const doc = await UserModel.findOne({ email: request.body.email });
if(!doc) {
response.status(404).send('email not found');
return;
}
const passValidation = doc.comparePassword(request.body.password);
if(passValidation) {
response.send('ok PASS');
} else {
response.status(401).send('password is not correct');
}
});
// เริ่มการทำงาน
app.listen(port, function () {
console.log('ตอนนี้เซิฟเวอร์ทำงานอยู่ที่ http://localhost:' + port);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment