mirror of
https://github.com/ArthurDanjou/artdanj-api.git
synced 2026-01-14 20:19:26 +01:00
Adapt post likes
This commit is contained in:
@@ -1,6 +1,5 @@
|
||||
import Post from "App/Models/Post";
|
||||
import {HttpContextContract} from "@ioc:Adonis/Core/HttpContext";
|
||||
import Redis from "@ioc:Adonis/Addons/Redis";
|
||||
|
||||
export default class PostsController {
|
||||
|
||||
@@ -17,37 +16,8 @@ export default class PostsController {
|
||||
return post.likes
|
||||
}
|
||||
|
||||
public async unlike ({request, params}: HttpContextContract) {
|
||||
const post = await Post.findByOrFail('slug', params.slug)
|
||||
const ip = await request.ip()
|
||||
|
||||
const getLikes = post.likes - 1
|
||||
const isLiked = await Redis.exists(`posts:${post.slug}/${ip}`)
|
||||
|
||||
if (isLiked) {
|
||||
await Redis.del(`posts:${post.slug}/${ip}`)
|
||||
await post.merge({
|
||||
likes: getLikes
|
||||
}).save()
|
||||
return {
|
||||
code: 200,
|
||||
post
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public async isLiked ({params, request}: HttpContextContract) {
|
||||
const post = await Post.findBy('slug', params.slug)
|
||||
if (post) {
|
||||
const ip = request.ip()
|
||||
return Redis.exists(`posts:${post.slug}/${ip}`);
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
public async like ({request, params}: HttpContextContract) {
|
||||
public async like ({params, response}: HttpContextContract) {
|
||||
let post = await Post.findBy('slug', params.slug)
|
||||
const ip = await request.ip()
|
||||
|
||||
if (!post) {
|
||||
post = await Post.create({
|
||||
@@ -57,18 +27,13 @@ export default class PostsController {
|
||||
}
|
||||
|
||||
const getLikes = post.likes + 1
|
||||
const isLiked = await Redis.exists(`posts:${post.slug}/${ip}`)
|
||||
|
||||
if (!isLiked) {
|
||||
await Redis.set(`posts:${post.slug}/${ip}`, Date.now())
|
||||
await post.merge({
|
||||
likes: getLikes
|
||||
}).save()
|
||||
return {
|
||||
code: 200,
|
||||
post
|
||||
}
|
||||
}
|
||||
await post.merge({
|
||||
likes: getLikes
|
||||
}).save()
|
||||
return response.status(200).send({
|
||||
post
|
||||
})
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -75,7 +75,5 @@ Route.group(() => {
|
||||
// ArtSite
|
||||
Route.group(() => {
|
||||
Route.get('/:slug', 'PostsController.getLikes')
|
||||
Route.get('/is/:slug', 'PostsController.isLiked')
|
||||
Route.post('/:slug/like', 'PostsController.like')
|
||||
Route.post('/:slug/unlike', 'PostsController.unlike')
|
||||
}).prefix('posts')
|
||||
|
||||
Reference in New Issue
Block a user