Add API endpoint to fetch team

This commit is contained in:
2020-11-04 21:18:47 -06:00
parent d1d12663a7
commit 3befe69f30
7 changed files with 184 additions and 36 deletions

View File

@@ -0,0 +1,36 @@
const { Model } = require('flitter-orm')
/*
* Player Model
* -------------------------------------------------------------
*/
class Player extends Model {
static get services() {
return [...super.services, 'output', 'models']
}
/*
* Define the flitter-orm schema of the model.
*/
static get schema() {
return {
player_number: String,
player_name: String,
player_position: String,
team_name: String,
image_url: String,
}
}
async to_api() {
return {
player_number: this.player_number,
player_name: this.player_name,
player_position: this.player_position,
team_name: this.team_name,
image_url: this.image_url,
}
}
}
module.exports = exports = Player

View File

@@ -6,7 +6,7 @@ const { Model } = require('flitter-orm')
*/
class Team extends Model {
static get services() {
return [...super.services, 'output']
return [...super.services, 'output', 'models']
}
/*
@@ -20,6 +20,46 @@ class Team extends Model {
player_ids: [String],
}
}
/**
* Look up or create a team for the given user.
* @param {User} user
* @return {Promise<Team>}
*/
static async getForUser(user) {
// try to find an existing team first
const existing_team = await this.findOne({ user_id: user.id })
if ( existing_team ) return existing_team
// otherwise create a team for the user
const new_team = new this({
user_id: user.id,
team_name: `${user.uid}'s team`,
player_ids: [],
})
// Generate the next team number
const highest_num_team = await this.sort('-team_num').findOne()
if ( highest_num_team ) {
new_team.team_num = highest_num_team.team_num + 1
} else {
new_team.team_num = 1
}
await new_team.save()
return new_team
}
async to_api() {
const User = this.models.get('auth:User')
return {
user_id: this.user_id,
user_display: (await User.findById(this.user_id))?.uid || 'Unknown User',
team_name: this.team_name,
team_num: this.team_num,
}
}
}
module.exports = exports = Team