When you create games or any competitive webapp on Koji, you need to have Leaderboards. Setting them up in the backend could sometimes be a horrific task. So, you have this simple plugNplay Express API that runs smoothly with the most minimal setup!
To install the API on your Node.js backend, run the following.
$ npm i -S koji-leaderboard-api
kojiLeaderboardApi(app, 'leaderboard')
- 1st parameter:
app
π (type:Express App Instance
, Required) - 2nd parameter:
tableName
π (type:String
, Optional, Default:leaderboard
) - The table name you want your data to be stored under. For eg. if yourtableName
isleaderboard
, then your API endpoints will beGET /leaderboard
andPOST /leaderboard
.
See the following example π
import express from 'express'
import bodyParser from 'body-parser'
import kojiLeaderboardApi from 'koji-leaderboard-api' // The library you are using
const app = express() // This is the Express App Instance
// Body parser
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
limit: '2mb',
extended: true,
}))
// CORS
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', '*') // use '*' as second param to allow any client to hack in
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization, X-Jiro-Request-Tag')
next()
})
/**
* @name kojiLeaderboardApi
* @description Doing `kojiLeaderboardApi(app)` activates the `/leaderboard` GET and POST API endpoints
* that your frontend can use to Display and Update Leaderboard
*
* @param {Express App Instance} app - (required)
* @param {String} tableName - (optional) Default: `leaderboard`
*/
kojiLeaderboardApi(app)
// Listen on Port 8080. Visit http://localhost:8080 to see the backend.
app.listen(8080, null, async err => {
if (err) console.log(err.message)
console.log('[koji] Backend Started π')
})
In the above example, we make use of an express server. What you need to do, is to just pass the Express App Instance
as the only parameter to the kojiLeaderboardApi()
function. That activates your Leaderboard API.
Method | Endpoint | Parameters (JSON Body) | |
---|---|---|---|
1 | GET | /leaderboard |
- |
2 | POST | /leaderboard |
name: String π required score: Number π required privateAttributes: Object π optional |
Important note: The above mentioned API endpoints only work if you haven't filled in the second parameter. If you have, the second parameter will be your GET and POST endpoint.
import Koji from 'koji-tools'
async function fetchData() {
const response = await fetch(`${Koji.config.serviceMap.backend}/leaderboard`)
.then(response => response.json())
.catch(err => throw new Error('Fetch Error: ', err))
return response
}
{
"success": true,
"scores": [
{
"name": "Rafa",
"score": 4766,
"dateCreated": 1567290764
},
{
"name": "Sean",
"score": 833,
"dateCreated": 1567178966
}
]
}
The parameters have to be a Body in a JSON format, to be processed correctly.
name
π String: { strLength should be more than 3 } (required)score
π Number: { Score should be more than 1 } (required)privateAttributes
π Object or null (optional) The Object can contain email, or any private information that shouldn't be accessed from theGET /leaderboard
endpoint.
import Koji from 'koji-tools'
async function saveData() {
const body = {
name: "Kumar Abhirup",
score: 5280,
privateAttributes: {
email: "[email protected]"
},
}
await fetch(`${Koji.config.serviceMap.backend}/leaderboard`, {
method: 'post',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
})
.then(response => response.json())
.then(jsonResponse => {
console.log(jsonResponse) // see example response
})
.catch(err => {
console.log(err)
})
}
{
"success": true,
"data": {
"name": "Kumar Abhirup",
"score": 5280,
"privateAttributes": {
"email": "[email protected]"
},
"dateCreated": 1567186095
}
}
MIT Β© Kumar Abhirup
Follow me π on Twitter β