ddstats-server/api/players.js

80 lines
2.0 KiB
JavaScript

import { Router } from 'express'
import Player from '../schemas/Player.js'
const playerApi = Router()
playerApi.get(
'/count',
(req, res) => {
Player.count({}).then(
playerAmount => {
res.json({
success: true,
response: playerAmount
})
}
)
}
)
playerApi.get(
'/get/:player',
(req, res) => {
Player.findOne({ name: req.params.player }).then(
player => {
if (!player)
return res.json({
success: false,
response: "No player found!"
})
res.json({
success: true,
response: player
})
}
)
}
)
playerApi.get(
'/search',
async (req, res) => {
if (!req.query.q)
return res.json({
success: false,
response: "No query ('host/path?q=query') provided!"
})
const name = req.query.q
const sort = req.query.sort ?? 'name'
const order = req.query.order === "desc" ? -1 : 1
const page = req.query.page ?? 1
const pageCount = Math.ceil((await Player.find({ name: { $regex: name, $options: 'i' }}).count()) / 20)
Player.find({ name: { $regex: name, $options: 'i' }}).sort([[sort, order]]).limit(20).skip((page - 1) * 20).then(
players => {
if (!players[0])
return res.json({
success: false,
response: "No players found!"
})
res.json({
success: true,
response: {
pageCount,
players
}
})
}
)
}
)
/**
* This module handles all API actions related to players.
* @module api/players
*/
export default playerApi