Adapt post likes

This commit is contained in:
2021-04-08 10:50:58 +02:00
parent fcf80f5e85
commit 59835db2bd
2 changed files with 7 additions and 44 deletions

View File

@@ -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
})
}
}

View File

@@ -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')