Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Server - Muhammad Ridho Hauzan #19

Open
wants to merge 37 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
37 commits
Select commit Hold shift + click to select a range
3d0f505
Project Init
rdhhauzan Nov 8, 2022
2ba0dd8
Set associations
rdhhauzan Nov 8, 2022
820570a
add jwt & bcryptjs helpers
rdhhauzan Nov 8, 2022
ff3ad1b
User BeforeCreate Hooks
rdhhauzan Nov 8, 2022
c3cc8b9
Register Feature Done
rdhhauzan Nov 8, 2022
b339407
Merge pull request #1 from rdhhauzan/feature-register
rdhhauzan Nov 8, 2022
79e00bf
Main Feature: Register Done
rdhhauzan Nov 8, 2022
c345a93
Merge pull request #2 from rdhhauzan/feature-login
rdhhauzan Nov 8, 2022
b7fdc7c
Merge pull request #3 from rdhhauzan/feature-login
rdhhauzan Nov 8, 2022
adf750d
revert change in main
rdhhauzan Nov 8, 2022
39af3ec
fix: fix package.json
rdhhauzan Nov 8, 2022
343fa34
Authentication Done
rdhhauzan Nov 9, 2022
956cc5a
Merge pull request #4 from rdhhauzan/feature-authentication
rdhhauzan Nov 9, 2022
eccb251
Fetch Data From API Route
rdhhauzan Nov 9, 2022
74cc216
Merge pull request #5 from rdhhauzan/feature-FetchDataFromApi
rdhhauzan Nov 9, 2022
290e3ca
new dependencies : axios
rdhhauzan Nov 9, 2022
931de01
Fetch News From NewsAPI
rdhhauzan Nov 9, 2022
45c5a48
Merge pull request #6 from rdhhauzan/feature-FetchNewsFromApi
rdhhauzan Nov 9, 2022
63ff70f
Search News From API Done
rdhhauzan Nov 9, 2022
1e44c84
Merge pull request #7 from rdhhauzan/feature-SearchNews
rdhhauzan Nov 9, 2022
72ed25d
new dependencies: midtrans-client
rdhhauzan Nov 9, 2022
88644ad
User payment Function, If Success Change isPremium to true
rdhhauzan Nov 9, 2022
5a939b8
Merge pull request #8 from rdhhauzan/feature-payment
rdhhauzan Nov 9, 2022
8e3edb5
Add Payment Authorization
rdhhauzan Nov 9, 2022
8de4b9d
Add Post For Premium User Done
rdhhauzan Nov 9, 2022
7011b35
Merge pull request #9 from rdhhauzan/feature-addPost
rdhhauzan Nov 9, 2022
c1be266
Edit Authorization
rdhhauzan Nov 9, 2022
4c629ce
Edit Post Done
rdhhauzan Nov 9, 2022
8fedbdd
Post Comment Done
rdhhauzan Nov 9, 2022
259560e
Get User Post + Comment Done
rdhhauzan Nov 9, 2022
a486b4f
Validation
rdhhauzan Nov 9, 2022
6ebe28d
Fetch Post By ID done
rdhhauzan Nov 9, 2022
003546b
fix: get logged in user post
rdhhauzan Nov 9, 2022
fbdc290
fix: search news
rdhhauzan Nov 9, 2022
9520552
Delete Post Done
rdhhauzan Nov 9, 2022
78df6bd
Cleanup Code & fix Midtrans
rdhhauzan Nov 10, 2022
02a00ef
merge
rdhhauzan Nov 10, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
The table of contents is too big for display.
Diff view
Diff view
  •  
  •  
  •  
The diff you're trying to view is too large. We only load the first 3000 changed files.
365 changes: 365 additions & 0 deletions Controller/controllers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,365 @@
const { comparePassword } = require("../helpers/bcrypt");
const { createToken } = require("../helpers/jwt");
const { User, Comment, Post } = require("../models/index");
const axios = require("axios");
const { JSDOM } = require("jsdom");
const { Readability } = require("@mozilla/readability");
const midtransClient = require("midtrans-client");

class Controller {
static async registerUser(req, res) {
let { email, username, password } = req.body;
// console.log(req.body);
try {
let data = await User.create({
email: email,
username: username,
password: password,
});

res.status(201).json({
id: data.id,
email: data.email,
username: data.username,
});
} catch (error) {
if (
error.name === "SequelizeValidationError" ||
error.name === "SequelizeUniqueConstraintError"
) {
error.errors.map((el) => {
res.status(401).json({ message: el.message });
});
}
}
}

static async loginUser(req, res) {
let { email, password } = req.body;
// console.log(req.body);
try {
let findUser = await User.findOne({
where: {
email: email,
},
});
if (!findUser) {
throw { name: "USER_NOT_FOUND" };
}

let validatePassword = comparePassword(password, findUser.password);
if (!validatePassword) {
throw { name: "USER_NOT_FOUND" };
}

const payload = {
id: findUser.id,
email: findUser.email,
username: findUser.username,
isPremium: findUser.isPremium,
};

const access_token = createToken(payload);
res.status(200).json({
access_token: access_token,
id: findUser.id,
email: findUser.email,
username: findUser.username,
isPremium: findUser.isPremium,
});
} catch (error) {
if (error.name === "USER_NOT_FOUND") {
res.status(401).json({
message: "Invalid Email/Password",
});
}
}
}

static async fetchDataFromApi(req, res) {
let { page } = req.query;
try {
let { data } = await axios.get(
`https://www.newsapi.ai/api/v1/article/getArticles?query=%7B%22%24query%22%3A%7B%22%24and%22%3A%5B%7B%22locationUri%22%3A%22http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FIndonesia%22%7D%2C%7B%22dateStart%22%3A%222022-11-05%22%2C%22dateEnd%22%3A%222022-11-09%22%2C%22lang%22%3A%22ind%22%7D%5D%7D%2C%22%24filter%22%3A%7B%22dataType%22%3A%5B%22news%22%5D%7D%7D&resultType=articles&articlesSortBy=date&articlesCount=20&articleBodyLen=-1&apiKey=1ac04d32-99c0-4172-a7d0-c2b7b1988e95&articlesPage=${page}`
);
res.status(200).json(data);
} catch (error) {
console.log(error);
}
}

static async searchNews(req, res) {
// let { search } = req.body;
let { page, search } = req.query;
const options = {
method: "GET",
url: "https://newscatcher.p.rapidapi.com/v1/search_enterprise",
params: {
q: `${search}`,
lang: "id",
sort_by: "relevancy",
page: `${page}`,
media: "True",
page_size: "20",
},
headers: {
"X-RapidAPI-Key": "832bfe4441msha6c9d57ff9ea7f5p1087cfjsn9563c7304789",
"X-RapidAPI-Host": "newscatcher.p.rapidapi.com",
},
};

axios
.request(options)
.then(function (response) {
// console.log(response.data);
res.status(200).json(response.data);
})
.catch(function (error) {
console.error(error);
});
}

static async userPayment(req, res) {
// Create Snap API instance
let snap = new midtransClient.Snap({
// Set to true if you want Production Environment (accept real transaction).
isProduction: false,
serverKey: "SB-Mid-server-nU1WKAwolq2Zzv-eKVov7L65",
});

let parameter = {
transaction_details: {
order_id: "YOUR-ORDERID-" + Math.floor(Math.random() * 500000),
gross_amount: 3000,
},
credit_card: {
secure: true,
},
customer_details: {
email: req.user.email,
},
};

snap.createTransaction(parameter).then((transaction) => {
// transaction token
let transactionToken = transaction.token;
let transactionUrl = transaction.redirect_url;
// console.log("transactionToken:", transactionToken);
res.status(200).json({
transactionToken: transactionToken,
redirect_url: transactionUrl,
});
});
// res.redirect(200, transactionUrl);
}

static async addPost(req, res) {
console.log(req.user);
let { title, content, imageUrl, tag } = req.body;
try {
if (!title || !content || !imageUrl || !tag) {
throw { name: "DATA_NOT_COMPLETE" };
}
let data = await Post.create({
title: title,
content: content,
imageUrl: imageUrl,
tag: tag,
UserId: req.user.id,
});

// res.status(201).json(data)
res.status(201).json({ message: "Post Add Successfully!" });
} catch (error) {
if (error.name === "DATA_NOT_COMPLETE") {
res.status(403).json({ message: "Please Fill All the Fields!" });
}
console.log(error);
}
}

static async editPost(req, res) {
// console.log('aaaaaa');
let { title, content, imageUrl, tag } = req.body;
let PostId = req.params.id;
try {
if (!title || !content || !imageUrl || !tag) {
throw { name: "DATA_NOT_COMPLETE" };
}
let data = await Post.update(
{
title: title,
content: content,
imageUrl: imageUrl,
tag: tag,
UserId: req.user.id,
},
{
where: {
id: PostId,
},
}
);

// res.status(201).json(data)
res.status(201).json({ message: "Post Edit Successfully!" });
} catch (error) {
if (error.name === "DATA_NOT_COMPLETE") {
res.status(403).json({ message: "Please Fill All the Fields!" });
}
console.log(error);
}
}

static async commentPost(req, res) {
let PostId = req.params.postId;
let { comment } = req.body;
try {
let data = await Comment.create({
UserId: req.user.id,
PostId: PostId,
comment: comment,
});

res.status(201).json({
message: "Comment Add Successfully",
});
} catch (error) {}
}

static async fetchNewsFromDB(req, res) {
const query = {};
let limit = 20;
let offset;
const getPagingData = (data, page, limit) => {
const { count: totalItems, rows: rows } = data;
// console.log(data);
const currentPage = page ? +page : 0;
const totalPages = Math.ceil(totalItems / limit);

return { totalItems, rows, totalPages, currentPage };
};

const { page } = req.query;
if (page !== "" && typeof page !== "undefined") {
offset = page * limit - limit;
query.offset = offset;
query.limit = limit;
} else {
limit = 20;
offset = 0;
query.limit = limit;
query.offset = offset;
}

query.include = [
{
model: Comment,
include: {
model: User,
},
},
];

try {
let data = await Post.findAndCountAll(query);

res.status(200).json(getPagingData(data, page, limit));
} catch (error) {
console.log(error);
}
}

static async getUserPost(req, res) {
const query = {};
let limit = 20;
let offset;
const getPagingData = (data, page, limit) => {
const { count: totalItems, rows: rows } = data;
// console.log(data);
const currentPage = page ? +page : 0;
const totalPages = Math.ceil(totalItems / limit);

return { totalItems, rows, totalPages, currentPage };
};

const { page } = req.query;
if (page !== "" && typeof page !== "undefined") {
offset = page * limit - limit;
query.offset = offset;
query.limit = limit;
} else {
limit = 20;
offset = 0;
query.limit = limit;
query.offset = offset;
}

query.where = {
UserId: req.user.id,
};
try {
let data = await Post.findAndCountAll(query);

res.status(200).json(getPagingData(data, page, limit));
} catch (error) {
console.log(error);
}
}

static async getNewsById(req, res) {
let { id } = req.params;
try {
let data = await Post.findByPk(id, {
include: [
{
model: Comment,
include: {
model: User,
},
},
{
model: User,
},
],
});

res.status(200).json(data);
} catch (error) {}
}

static async deletePost(req, res) {
let { postId } = req.params;
try {
await Post.destroy({
where: {
UserId: req.user.id,
id: postId,
},
});

res.status(200).json({
message: "Post Delete Successfully!"
})
} catch (error) {
console.log(error);
}
}

static async userUpdateStatus (req, res) {
try {
await User.update(
{ isPremium: true },
{
where: {
id: req.user.id,
},
}
);
} catch (error) {
console.log(error);
}
}
}

module.exports = Controller;
Loading