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

Player groups API #346

Merged
merged 3 commits into from
Oct 18, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/config/api-routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import apiKeyMiddleware from '../middlewares/api-key-middleware'
import playerAuthMiddleware from '../middlewares/player-auth-middleware'
import PlayerAuthAPIService from '../services/api/player-auth-api.service'
import continunityMiddleware from '../middlewares/continunity-middleware'
import PlayerGroupAPIService from '../services/api/player-group-api.service'

export default (app: Koa) => {
app.use(apiKeyMiddleware)
Expand All @@ -31,6 +32,7 @@ export default (app: Koa) => {
app.use(playerAuthMiddleware)
app.use(continunityMiddleware)

app.use(service('/v1/player-groups', new PlayerGroupAPIService()))
app.use(service('/v1/health-check', new HealthCheckAPIService()))
app.use(service('/v1/game-feedback', new GameFeedbackAPIService()))
app.use(service('/v1/game-config', new GameConfigAPIService()))
Expand Down
88 changes: 88 additions & 0 deletions src/docs/player-group-api.docs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
import PlayerGroupAPIService from '../services/api/player-group-api.service'
import APIDocs from './api-docs'

const PlayerGroupAPIDocs: APIDocs<PlayerGroupAPIService> = {
get: {
description: 'Get a group and its members',
params: {
route: {
id: 'The ID of the group'
}
},
samples: [
{
title: 'Sample response (members visible)',
sample: {
group: {
id: '74b6a013-6c3d-4de6-8f61-444b4cf6e909',
name: 'Online players',
description: 'Players that are currently online',
rules: [
{
name: 'EQUALS',
negate: false,
field: 'props.online',
castType: 'CHAR',
operands: [
'true'
]
}
],
ruleMode: '$and',
membersVisible: true,
updatedAt: '2024-10-01T23:09:18.000Z',
count: 1,
members: [
{
id: '714b38f5-1dee-4243-a54c-50fb1cfe2e4e',
props: [
{
key: 'online',
value: 'true'
}
],
aliases: [],
devBuild: false,
createdAt: '2024-09-29T14:14:34.000Z',
lastSeenAt: '2024-10-03T08:03:16.000Z',
groups: [
{
id: '74b6a013-6c3d-4de6-8f61-444b4cf6e909',
name: 'Online players'
}
]
}
]
}
}
},
{
title: 'Sample response (members not visible)',
sample: {
group: {
id: '74b6a013-6c3d-4de6-8f61-444b4cf6e909',
name: 'Online players',
description: 'Players that are currently online',
rules: [
{
name: 'EQUALS',
negate: false,
field: 'props.online',
castType: 'CHAR',
operands: [
'true'
]
}
],
ruleMode: '$and',
membersVisible: false,
updatedAt: '2024-10-01T23:09:18.000Z',
count: 1
}
}
}
]
}
}

export default PlayerGroupAPIDocs
1 change: 1 addition & 0 deletions src/entities/api-key.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import Game from './game'
import User from './user'

export enum APIKeyScope {
READ_PLAYER_GROUPS = 'read:playerGroups',
WRITE_CONTINUITY_REQUESTS = 'write:continuityRequests',
READ_GAME_FEEDBACK = 'read:gameFeedback',
WRITE_GAME_FEEDBACK = 'write:gameFeedback',
Expand Down
12 changes: 12 additions & 0 deletions src/entities/player-group.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,10 @@ export default class PlayerGroup {
@Property()
description: string

@Required()
@Property({ default: false })
membersVisible: boolean

@Required({
validation: rulesValidation
})
Expand Down Expand Up @@ -103,7 +107,15 @@ export default class PlayerGroup {
description: this.description,
rules: this.rules,
ruleMode: this.ruleMode,
membersVisible: this.membersVisible,
updatedAt: this.updatedAt
}
}

async toJSONWithCount() {
return {
...this.toJSON(),
count: await this.members.loadCount()
}
}
}
11 changes: 11 additions & 0 deletions src/migrations/.snapshot-gs_dev.json
Original file line number Diff line number Diff line change
Expand Up @@ -791,6 +791,17 @@
"length": 255,
"mappedType": "string"
},
"members_visible": {
"name": "public",
"type": "tinyint(1)",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"length": 1,
"default": "false",
"mappedType": "boolean"
},
"rules": {
"name": "rules",
"type": "json",
Expand Down
13 changes: 13 additions & 0 deletions src/migrations/20241014202844AddPlayerGroupMembersVisibleColumn.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { Migration } from '@mikro-orm/migrations'

export class AddPlayerGroupMembersVisibleColumn extends Migration {

override async up(): Promise<void> {
this.addSql('alter table `player_group` add `members_visible` tinyint(1) not null default false;')
}

override async down(): Promise<void> {
this.addSql('alter table `player_group` drop column `members_visible`;')
}

}
5 changes: 5 additions & 0 deletions src/migrations/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import { UpdatePlayerAliasServiceColumn } from './20240916213402UpdatePlayerAlia
import { AddPlayerAliasAnonymisedColumn } from './20240920121232AddPlayerAliasAnonymisedColumn'
import { AddLeaderboardEntryPropsColumn } from './20240922222426AddLeaderboardEntryPropsColumn'
import { CreateUserPinnedGroupsTable } from './20241001194252CreateUserPinnedGroupsTable'
import { AddPlayerGroupMembersVisibleColumn } from './20241014202844AddPlayerGroupMembersVisibleColumn'

export default [
{
Expand Down Expand Up @@ -159,5 +160,9 @@ export default [
{
name: 'CreateUserPinnedGroupsTable',
class: CreateUserPinnedGroupsTable
},
{
name: 'AddPlayerGroupMembersVisibleColumn',
class: AddPlayerGroupMembersVisibleColumn
}
]
21 changes: 21 additions & 0 deletions src/policies/api/player-group-api.policy.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import Policy from '../policy'
import { PolicyDenial, PolicyResponse, Request } from 'koa-clay'
import { APIKeyScope } from '../../entities/api-key'
import PlayerGroup from '../../entities/player-group'

export default class PlayerGroupAPIPolicy extends Policy {
async get(req: Request): Promise<PolicyResponse> {
const { id } = req.params

const key = await this.getAPIKey()
const group = await this.em.getRepository(PlayerGroup).findOne({
id,
game: key.game
})

this.ctx.state.group = group
if (!group) return new PolicyDenial({ message: 'Group not found' }, 404)

return await this.hasScope(APIKeyScope.READ_PLAYER_GROUPS)
}
}
28 changes: 28 additions & 0 deletions src/services/api/player-group-api.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { HasPermission, Request, Response, Docs } from 'koa-clay'
import APIService from './api-service'
import PlayerGroupAPIPolicy from '../../policies/api/player-group-api.policy'
import PlayerGroup from '../../entities/player-group'
import Player from '../../entities/player'
import PlayerGroupAPIDocs from '../../docs/player-group-api.docs'

type PlayerGroupWithCountAndMembers = Pick<PlayerGroup, 'id' | 'name' | 'description' | 'rules' | 'ruleMode' | 'updatedAt'> & { count: number, members?: Player[] }

export default class PlayerGroupAPIService extends APIService {
@HasPermission(PlayerGroupAPIPolicy, 'get')
@Docs(PlayerGroupAPIDocs.get)
async get(req: Request): Promise<Response> {
const group: PlayerGroup = req.ctx.state.group

const groupWithCountAndMembers: PlayerGroupWithCountAndMembers = await group.toJSONWithCount()
if (group.membersVisible) {
groupWithCountAndMembers.members = await group.members.loadItems()
}

return {
status: 200,
body: {
group: groupWithCountAndMembers
}
}
}
}
23 changes: 8 additions & 15 deletions src/services/player-group.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@ import PlayerGroupPolicy from '../policies/player-group.policy'
import getUserFromToken from '../lib/auth/getUserFromToken'
import UserPinnedGroup from '../entities/user-pinned-group'

type PlayerGroupWithCount = Pick<PlayerGroup, 'id' | 'name' | 'description' | 'rules' | 'ruleMode' | 'updatedAt'> & { count: number }

@Routes([
{
method: 'GET'
Expand Down Expand Up @@ -46,13 +44,6 @@ type PlayerGroupWithCount = Pick<PlayerGroup, 'id' | 'name' | 'description' | 'r
}
])
export default class PlayerGroupService extends Service {
private async groupWithCount(group: PlayerGroup): Promise<PlayerGroupWithCount> {
return {
...group.toJSON(),
count: await group.members.loadCount()
}
}

@HasPermission(PlayerGroupPolicy, 'index')
async index(req: Request): Promise<Response> {
const em: EntityManager = req.ctx.em
Expand All @@ -61,7 +52,7 @@ export default class PlayerGroupService extends Service {
return {
status: 200,
body: {
groups: await Promise.all(groups.map(this.groupWithCount))
groups: await Promise.all(groups.map((group) => group.toJSONWithCount()))
}
}
}
Expand All @@ -79,14 +70,15 @@ export default class PlayerGroupService extends Service {
@Validate({ body: [PlayerGroup] })
@HasPermission(PlayerGroupPolicy, 'post')
async post(req: Request): Promise<Response> {
const { name, description, ruleMode, rules } = req.body
const { name, description, ruleMode, rules, membersVisible } = req.body
const em: EntityManager = req.ctx.em

const group = new PlayerGroup(req.ctx.state.game)
group.name = name
group.description = description
group.ruleMode = ruleMode
group.rules = this.buildRulesFromData(rules)
group.membersVisible = membersVisible
await group.checkMembership(em)

createGameActivity(em, {
Expand All @@ -103,22 +95,23 @@ export default class PlayerGroupService extends Service {
return {
status: 200,
body: {
group: await this.groupWithCount(group)
group: await group.toJSONWithCount()
}
}
}

@Validate({ body: [PlayerGroup] })
@HasPermission(PlayerGroupPolicy, 'put')
async put(req: Request): Promise<Response> {
const { name, description, ruleMode, rules } = req.body
const { name, description, ruleMode, rules, membersVisible } = req.body
const em: EntityManager = req.ctx.em

const group: PlayerGroup = req.ctx.state.group
group.name = name
group.description = description
group.ruleMode = ruleMode
group.rules = this.buildRulesFromData(rules)
group.membersVisible = membersVisible
await group.checkMembership(em)

createGameActivity(em, {
Expand All @@ -135,7 +128,7 @@ export default class PlayerGroupService extends Service {
return {
status: 200,
body: {
group
group: await group.toJSONWithCount()
}
}
}
Expand Down Expand Up @@ -260,7 +253,7 @@ export default class PlayerGroupService extends Service {
orderBy: { createdAt: 'desc' }
})

const groups = await Promise.all(pinnedGroups.map(({ group }) => this.groupWithCount(group)))
const groups = await Promise.all(pinnedGroups.map(({ group }) => group.toJSONWithCount()))

return {
status: 200,
Expand Down
Loading