重構成員管理部分
This commit is contained in:
+24
@@ -0,0 +1,24 @@
|
||||
package club.sakunadaisuki.pcrediveclanrecordbackend.database.dto
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
import kotlinx.serialization.json.Json
|
||||
import org.bson.Document
|
||||
|
||||
@Serializable
|
||||
data class MemberDto(
|
||||
var uid: String,
|
||||
val playerName: String,
|
||||
val nickName: String,
|
||||
val discordID: String,
|
||||
var leave: Boolean = false,
|
||||
var createAt: Long? = null,
|
||||
var updatedAt: Long? = null
|
||||
) {
|
||||
fun toDocument(): Document = Document.parse(Json.encodeToString(this))
|
||||
|
||||
companion object {
|
||||
private val json = Json { ignoreUnknownKeys = true }
|
||||
|
||||
fun fromDocument(document: Document): MemberDto = json.decodeFromString(document.toJson())
|
||||
}
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
package club.sakunadaisuki.pcrediveclanrecordbackend.database.service
|
||||
|
||||
import club.sakunadaisuki.pcrediveclanrecordbackend.database.dto.MemberDto
|
||||
import com.mongodb.client.MongoCollection
|
||||
import com.mongodb.client.MongoDatabase
|
||||
import com.mongodb.client.model.Filters
|
||||
import kotlinx.coroutines.Dispatchers
|
||||
import kotlinx.coroutines.withContext
|
||||
import org.bson.Document
|
||||
|
||||
class MemberService(private val database: MongoDatabase) {
|
||||
var collection: MongoCollection<Document>
|
||||
|
||||
init {
|
||||
database.createCollection("member")
|
||||
collection = database.getCollection("member")
|
||||
}
|
||||
|
||||
// Create new car
|
||||
suspend fun create(data: MemberDto): String = withContext(Dispatchers.IO) {
|
||||
data.createAt = System.currentTimeMillis()
|
||||
data.updatedAt = System.currentTimeMillis()
|
||||
data.leave = false
|
||||
val doc = data.toDocument()
|
||||
collection.insertOne(doc)
|
||||
doc["uid"].toString()
|
||||
}
|
||||
|
||||
// Read a car
|
||||
suspend fun read(): List<MemberDto> = withContext(Dispatchers.IO) {
|
||||
collection.find().toList().map(MemberDto::fromDocument)
|
||||
}
|
||||
|
||||
// Read a car
|
||||
suspend fun read(uid: String): MemberDto? = withContext(Dispatchers.IO) {
|
||||
collection.find(Filters.eq("uid", uid)).first()?.let(MemberDto::fromDocument)
|
||||
}
|
||||
|
||||
// Update a car
|
||||
suspend fun update(uid: String, data: MemberDto): Document? = withContext(Dispatchers.IO) {
|
||||
collection.findOneAndReplace(Filters.eq("uid", uid), data.toDocument())
|
||||
}
|
||||
|
||||
// Delete a car
|
||||
suspend fun delete(uid: String): Document? = withContext(Dispatchers.IO) {
|
||||
collection.findOneAndDelete(Filters.eq("uid", uid))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package club.sakunadaisuki.pcrediveclanrecordbackend
|
||||
|
||||
import io.ktor.server.netty.EngineMain
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
EngineMain.main(args)
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package club.sakunadaisuki.pcrediveclanrecordbackend.mapper
|
||||
|
||||
import club.sakunadaisuki.pcrediveclanrecordbackend.database.dto.MemberDto
|
||||
import club.sakunadaisuki.pcrediveclanrecordbackend.model.Member
|
||||
|
||||
fun Member.toDto(): MemberDto {
|
||||
return MemberDto(
|
||||
uid = uid,
|
||||
playerName = playerName,
|
||||
nickName = nickName,
|
||||
discordID = discordID,
|
||||
leave = leave,
|
||||
createAt = createAt,
|
||||
updatedAt = updatedAt,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package club.sakunadaisuki.pcrediveclanrecordbackend.model
|
||||
|
||||
data class Member(
|
||||
var uid: String,
|
||||
val playerName: String,
|
||||
val nickName: String,
|
||||
val discordID: String,
|
||||
var leave: Boolean = false,
|
||||
var createAt: Long? = null,
|
||||
var updatedAt: Long? = null
|
||||
)
|
||||
@@ -0,0 +1,30 @@
|
||||
package club.sakunadaisuki.pcrediveclanrecordbackend.plugins
|
||||
|
||||
import io.ktor.server.application.*
|
||||
import io.ktor.http.*
|
||||
import io.ktor.server.plugins.cors.routing.*
|
||||
import io.ktor.server.plugins.swagger.*
|
||||
import io.ktor.server.routing.*
|
||||
|
||||
fun Application.configureHttp() {
|
||||
install(CORS) {
|
||||
allowMethod(HttpMethod.Options)
|
||||
allowMethod(HttpMethod.Put)
|
||||
allowMethod(HttpMethod.Delete)
|
||||
allowMethod(HttpMethod.Patch)
|
||||
allowHeader(HttpHeaders.Authorization)
|
||||
allowHeader("MyCustomHeader")
|
||||
anyHost() // @TODO: Don't do this in production if possible. Try to limit it.
|
||||
}
|
||||
routing {
|
||||
swaggerUI(path = "openapi") {
|
||||
/*
|
||||
Documentation source configuration goes here.
|
||||
|
||||
This can be from file (documentation.yaml), or it can be served dynamically from your sources using the
|
||||
`describe {}` API on routes. When `openApi` enabled in Gradle, these calls will be automatically injected
|
||||
based on your code and comments.
|
||||
*/
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package club.sakunadaisuki.pcrediveclanrecordbackend.plugins
|
||||
|
||||
import club.sakunadaisuki.pcrediveclanrecordbackend.model.Member
|
||||
import club.sakunadaisuki.pcrediveclanrecordbackend.database.service.MemberService
|
||||
import club.sakunadaisuki.pcrediveclanrecordbackend.mapper.toDto
|
||||
import com.mongodb.client.*
|
||||
import io.ktor.http.*
|
||||
import io.ktor.server.application.*
|
||||
import io.ktor.server.config.tryGetString
|
||||
import io.ktor.server.request.*
|
||||
import io.ktor.server.response.*
|
||||
import io.ktor.server.routing.*
|
||||
|
||||
fun Application.configureMongo() {
|
||||
// Connect to your mongo instance
|
||||
val mongoDatabase = connectToMongoDB()
|
||||
val memberService = runCatching {
|
||||
MemberService(mongoDatabase)
|
||||
}.getOrNull() ?: return
|
||||
|
||||
routing {
|
||||
route("/api") {
|
||||
// Read member
|
||||
get("/member") {
|
||||
memberService.read().let { member ->
|
||||
call.respond(member)
|
||||
}
|
||||
}
|
||||
// Read member
|
||||
get("/member/{uid}") {
|
||||
val uid = call.parameters["uid"] ?: throw IllegalArgumentException("No ID found")
|
||||
memberService.read(uid)?.let { member ->
|
||||
call.respond(member)
|
||||
} ?: call.respond(HttpStatusCode.NotFound)
|
||||
}
|
||||
// Create member
|
||||
post("/member") {
|
||||
val member = call.receive<Member>()
|
||||
val id = memberService.create(member.toDto())
|
||||
call.respond(HttpStatusCode.Created, id)
|
||||
}
|
||||
// Update member
|
||||
put("/member/{uid}") {
|
||||
val uid = call.parameters["uid"] ?: throw IllegalArgumentException("No ID found")
|
||||
val member = call.receive<Member>()
|
||||
memberService.update(uid, member.toDto())?.let {
|
||||
call.respond(HttpStatusCode.OK)
|
||||
} ?: call.respond(HttpStatusCode.NotFound)
|
||||
}
|
||||
// Delete member
|
||||
delete("/member/{uid}") {
|
||||
val uid = call.parameters["uid"] ?: throw IllegalArgumentException("No ID found")
|
||||
memberService.delete(uid)?.let {
|
||||
call.respond(HttpStatusCode.OK)
|
||||
} ?: call.respond(HttpStatusCode.NotFound)
|
||||
}
|
||||
|
||||
// TODO Battle Record
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Establishes connection with a MongoDB database.
|
||||
*
|
||||
* The following configuration properties (in application.yaml/application.conf) can be specified:
|
||||
* * `db.mongo.user` username for your database
|
||||
* * `db.mongo.password` password for the user
|
||||
* * `db.mongo.host` host that will be used for the database connection
|
||||
* * `db.mongo.port` port that will be used for the database connection
|
||||
* * `db.mongo.maxPoolSize` maximum number of connections to a MongoDB server
|
||||
* * `db.mongo.database.name` name of the database
|
||||
*
|
||||
* IMPORTANT NOTE: in order to make MongoDB connection working, you have to start a MongoDB server first.
|
||||
* See the instructions here: https://www.mongodb.com/docs/manual/administration/install-community/
|
||||
* all the paramaters above
|
||||
*
|
||||
* @returns [MongoDatabase] instance
|
||||
* */
|
||||
fun Application.connectToMongoDB(): MongoDatabase {
|
||||
val user = environment.config.tryGetString("db.mongo.user")
|
||||
val password = environment.config.tryGetString("db.mongo.password")
|
||||
val host = environment.config.tryGetString("db.mongo.host") ?: "127.0.0.1"
|
||||
val port = environment.config.tryGetString("db.mongo.port") ?: "27017"
|
||||
val maxPoolSize = environment.config.tryGetString("db.mongo.maxPoolSize")?.toInt() ?: 20
|
||||
val databaseName = environment.config.tryGetString("db.mongo.database.name") ?: "pc_re_dive_clan_battle"
|
||||
|
||||
val credentials = user?.let { userVal -> password?.let { passwordVal -> "$userVal:$passwordVal@" } }.orEmpty()
|
||||
val uri = "mongodb://$credentials$host:$port/?maxPoolSize=$maxPoolSize&w=majority"
|
||||
|
||||
val mongoClient = MongoClients.create(uri)
|
||||
val database = mongoClient.getDatabase(databaseName)
|
||||
|
||||
monitor.subscribe(ApplicationStopped) {
|
||||
mongoClient.close()
|
||||
}
|
||||
|
||||
return database
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package club.sakunadaisuki.pcrediveclanrecordbackend.plugins
|
||||
|
||||
import io.ktor.server.application.*
|
||||
import io.ktor.server.response.*
|
||||
import io.ktor.server.routing.*
|
||||
|
||||
fun Application.configureRouting() {
|
||||
routing {
|
||||
get("/") {
|
||||
call.respondText("Hello, World!")
|
||||
}
|
||||
get("/json/kotlinx-serialization") {
|
||||
call.respond(mapOf("hello" to "world"))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package club.sakunadaisuki.pcrediveclanrecordbackend.plugins
|
||||
|
||||
import io.ktor.server.application.*
|
||||
import io.ktor.serialization.kotlinx.json.*
|
||||
import io.ktor.server.plugins.contentnegotiation.ContentNegotiation
|
||||
|
||||
fun Application.configureSerialization() {
|
||||
install(ContentNegotiation) {
|
||||
json()
|
||||
}
|
||||
}
|
||||
@@ -1,23 +0,0 @@
|
||||
package com.ray650128.pcredive
|
||||
|
||||
import ch.qos.logback.classic.Level
|
||||
import ch.qos.logback.classic.LoggerContext
|
||||
import io.ktor.server.application.*
|
||||
import com.ray650128.pcredive.plugins.*
|
||||
import org.slf4j.LoggerFactory
|
||||
|
||||
fun main(args: Array<String>) {
|
||||
val loggerContext = LoggerFactory.getILoggerFactory() as LoggerContext
|
||||
val rootLogger = loggerContext.getLogger("org.mongodb.driver")
|
||||
rootLogger.level = Level.OFF
|
||||
io.ktor.server.netty.EngineMain.main(args)
|
||||
}
|
||||
|
||||
@Suppress("unused") // application.conf references the main function. This annotation prevents the IDE from marking it as unused.
|
||||
fun Application.module() {
|
||||
configureUpdateTimer()
|
||||
configureHTTP()
|
||||
configureSerialization()
|
||||
configureMemberRouting()
|
||||
configureMemberRecordRouting()
|
||||
}
|
||||
@@ -1,40 +0,0 @@
|
||||
package com.ray650128.pcredive.database.dto
|
||||
|
||||
import com.ray650128.pcredive.database.model.Member
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class MemberDto(
|
||||
var _id: String? = null,
|
||||
var playerName: String,
|
||||
var nickName: String,
|
||||
var discordID: String,
|
||||
var uid: String,
|
||||
var leave: Boolean = false,
|
||||
var createAt: Long? = null,
|
||||
var updatedAt: Long? = null
|
||||
)
|
||||
|
||||
fun Member.toDto(): MemberDto {
|
||||
return MemberDto(
|
||||
_id = this._id.toString(),
|
||||
playerName = this.playerName,
|
||||
nickName = this.nickName,
|
||||
discordID = this.discordID,
|
||||
uid = this.uid,
|
||||
leave = this.leave,
|
||||
createAt = this.createAt,
|
||||
updatedAt = this.updatedAt
|
||||
)
|
||||
}
|
||||
|
||||
fun MemberDto.toMember(): Member =
|
||||
Member(
|
||||
playerName = this.playerName,
|
||||
nickName = this.nickName,
|
||||
discordID = this.discordID,
|
||||
uid = this.uid,
|
||||
leave = this.leave,
|
||||
createAt = this.createAt,
|
||||
updatedAt = this.updatedAt
|
||||
)
|
||||
@@ -1,49 +0,0 @@
|
||||
package com.ray650128.pcredive.database.dto
|
||||
|
||||
import com.ray650128.pcredive.database.model.Member
|
||||
import com.ray650128.pcredive.database.model.MemberRecord
|
||||
import com.ray650128.pcredive.database.model.Record
|
||||
import com.ray650128.pcredive.database.service.MemberService
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class MemberRecordDto(
|
||||
var _id: String? = null,
|
||||
var member: Member? = null,
|
||||
var record1: Record,
|
||||
var record1c: Record,
|
||||
var record2: Record,
|
||||
var record2c: Record,
|
||||
var record3: Record,
|
||||
var record3c: Record,
|
||||
var createdAt: Long?,
|
||||
var updatedAt: Long?
|
||||
)
|
||||
|
||||
fun MemberRecord.toDto(): MemberRecordDto {
|
||||
return MemberRecordDto(
|
||||
_id = this._id.toString(),
|
||||
member = MemberService.findById(this.memberId.toString()),
|
||||
record1 = this.record1,
|
||||
record1c = this.record1c,
|
||||
record2 = this.record2,
|
||||
record2c = this.record2c,
|
||||
record3 = this.record3,
|
||||
record3c = this.record3c,
|
||||
createdAt = this.createdAt,
|
||||
updatedAt = this.updatedAt
|
||||
)
|
||||
}
|
||||
|
||||
fun MemberRecordDto.toMemberRecord(): MemberRecord =
|
||||
MemberRecord(
|
||||
memberId = this.member?._id,
|
||||
record1 = this.record1,
|
||||
record1c = this.record1c,
|
||||
record2 = this.record2,
|
||||
record2c = this.record2c,
|
||||
record3 = this.record3,
|
||||
record3c = this.record3c,
|
||||
createdAt = this.createdAt,
|
||||
updatedAt = this.updatedAt
|
||||
)
|
||||
@@ -1,18 +0,0 @@
|
||||
package com.ray650128.pcredive.database.model
|
||||
|
||||
import kotlinx.serialization.Contextual
|
||||
import kotlinx.serialization.Serializable
|
||||
import org.litote.kmongo.Id
|
||||
import org.litote.kmongo.newId
|
||||
|
||||
@Serializable
|
||||
data class Member(
|
||||
@Contextual var _id: Id<Member> = newId(),
|
||||
var playerName: String,
|
||||
var nickName: String,
|
||||
var discordID: String,
|
||||
var uid: String,
|
||||
var leave: Boolean = false,
|
||||
var createAt: Long? = null,
|
||||
var updatedAt: Long? = null
|
||||
)
|
||||
@@ -1,26 +0,0 @@
|
||||
package com.ray650128.pcredive.database.model
|
||||
|
||||
import kotlinx.serialization.Contextual
|
||||
import kotlinx.serialization.Serializable
|
||||
import org.litote.kmongo.Id
|
||||
import org.litote.kmongo.newId
|
||||
|
||||
@Serializable
|
||||
data class MemberRecord(
|
||||
@Contextual var _id: Id<MemberRecord> = newId(),
|
||||
@Contextual var memberId: Id<Member>? = null,
|
||||
var record1: Record = Record(),
|
||||
var record1c: Record = Record(),
|
||||
var record2: Record = Record(),
|
||||
var record2c: Record = Record(),
|
||||
var record3: Record = Record(),
|
||||
var record3c: Record = Record(),
|
||||
var createdAt: Long? = null,
|
||||
var updatedAt: Long? = null
|
||||
)
|
||||
|
||||
@Serializable
|
||||
data class Record(
|
||||
var boss: String? = null,
|
||||
var damage: Int? = null
|
||||
)
|
||||
@@ -1,9 +0,0 @@
|
||||
package com.ray650128.pcredive.database.model
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class RecordData(
|
||||
val member: Member,
|
||||
var record: MemberRecord?
|
||||
)
|
||||
@@ -1,16 +0,0 @@
|
||||
package com.ray650128.pcredive.database.model
|
||||
|
||||
import kotlinx.serialization.Serializable
|
||||
|
||||
@Serializable
|
||||
data class UpdateMemberRecord(
|
||||
var memberId: String,
|
||||
var record1: Record = Record("未出"),
|
||||
var record1c: Record = Record("未出"),
|
||||
var record2: Record = Record("未出"),
|
||||
var record2c: Record = Record("未出"),
|
||||
var record3: Record = Record("未出"),
|
||||
var record3c: Record = Record("未出"),
|
||||
var createdAt: Long? = null,
|
||||
var updatedAt: Long? = null
|
||||
)
|
||||
@@ -1,58 +0,0 @@
|
||||
package com.ray650128.pcredive.database.service
|
||||
|
||||
import com.ray650128.pcredive.database.model.Member
|
||||
import com.ray650128.pcredive.database.model.MemberRecord
|
||||
import org.bson.types.ObjectId
|
||||
import org.litote.kmongo.*
|
||||
import org.litote.kmongo.id.toId
|
||||
|
||||
object MemberRecordService {
|
||||
private val client = KMongo.createClient("mongodb://ray650128:Zx0987062271!@192.168.50.128:27017")
|
||||
private val database = client.getDatabase("pc_re_dive_clan_battle")
|
||||
private val recordCollection = database.getCollection<MemberRecord>()
|
||||
|
||||
fun create(record: MemberRecord): Id<MemberRecord> {
|
||||
recordCollection.insertOne(record)
|
||||
return record._id
|
||||
}
|
||||
|
||||
fun findById(id: String): MemberRecord? {
|
||||
val bsonId: Id<MemberRecord> = ObjectId(id).toId()
|
||||
return recordCollection.findOne(MemberRecord::_id eq bsonId)
|
||||
}
|
||||
|
||||
fun findByMemberIdBetweenDate(id: String, start: Long, end: Long): MemberRecord? {
|
||||
val bsonId: Id<Member> = ObjectId(id).toId()
|
||||
return recordCollection.findOne(MemberRecord::memberId eq bsonId, MemberRecord::createdAt gte start, MemberRecord::createdAt lt end)
|
||||
}
|
||||
|
||||
fun findByTimeBetween(start: Long, end: Long): List<MemberRecord> {
|
||||
return recordCollection.find(MemberRecord::createdAt gte start, MemberRecord::createdAt lt end).toList()
|
||||
}
|
||||
|
||||
fun findByOwnerId(id: String): List<MemberRecord> {
|
||||
val bsonId: Id<Member> = ObjectId(id).toId()
|
||||
return recordCollection.find(MemberRecord::memberId eq bsonId).toList()
|
||||
}
|
||||
|
||||
fun updateById(id: String, request: MemberRecord): Boolean =
|
||||
findById(id)?.let { record ->
|
||||
val updateResult = recordCollection.replaceOne(
|
||||
record.copy(
|
||||
record1 = request.record1,
|
||||
record1c = request.record1c,
|
||||
record2 = request.record2,
|
||||
record2c = request.record2c,
|
||||
record3 = request.record3,
|
||||
record3c = request.record3c,
|
||||
updatedAt = System.currentTimeMillis()
|
||||
)
|
||||
)
|
||||
updateResult.modifiedCount == 1L
|
||||
} ?: false
|
||||
|
||||
fun deleteById(id: String): Boolean {
|
||||
val deleteResult = recordCollection.deleteOneById(ObjectId(id))
|
||||
return deleteResult.deletedCount == 1L
|
||||
}
|
||||
}
|
||||
@@ -1,52 +0,0 @@
|
||||
package com.ray650128.pcredive.database.service
|
||||
|
||||
import com.ray650128.pcredive.database.model.Member
|
||||
import org.bson.types.ObjectId
|
||||
import org.litote.kmongo.*
|
||||
import org.litote.kmongo.id.toId
|
||||
|
||||
object MemberService {
|
||||
private val client = KMongo.createClient("mongodb://ray650128:Zx0987062271!@192.168.50.128:27017")
|
||||
private val database = client.getDatabase("pc_re_dive_clan_battle")
|
||||
private val memberCollection = database.getCollection<Member>()
|
||||
|
||||
fun create(member: Member): Id<Member> {
|
||||
memberCollection.insertOne(member)
|
||||
return member._id
|
||||
}
|
||||
|
||||
//fun findAll(): List<Member> = memberCollection.find().toList()
|
||||
|
||||
fun findAll(isLeave: Boolean? = null): List<Member> {
|
||||
return if (isLeave == null) {
|
||||
memberCollection.find().toList()
|
||||
} else {
|
||||
memberCollection.find(Member::leave eq isLeave).toList()
|
||||
}
|
||||
}
|
||||
|
||||
fun findById(id: String): Member? {
|
||||
val bsonId: Id<Member> = ObjectId(id).toId()
|
||||
return memberCollection.findOne(Member::_id eq bsonId)
|
||||
}
|
||||
|
||||
fun updateById(id: String, request: Member): Boolean =
|
||||
findById(id)?.let { member ->
|
||||
val updateResult = memberCollection.replaceOne(
|
||||
member.copy(
|
||||
playerName = request.playerName,
|
||||
nickName = request.nickName,
|
||||
discordID = request.discordID,
|
||||
uid = request.uid,
|
||||
leave = request.leave,
|
||||
updatedAt = request.updatedAt
|
||||
)
|
||||
)
|
||||
updateResult.modifiedCount == 1L
|
||||
} ?: false
|
||||
|
||||
fun deleteById(id: String): Boolean {
|
||||
val deleteResult = memberCollection.deleteOneById(ObjectId(id))
|
||||
return deleteResult.deletedCount == 1L
|
||||
}
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
package com.ray650128.pcredive.plugins
|
||||
|
||||
import io.ktor.http.*
|
||||
import io.ktor.server.plugins.cors.routing.*
|
||||
import io.ktor.server.application.*
|
||||
import io.ktor.server.http.content.*
|
||||
import io.ktor.server.response.*
|
||||
import io.ktor.server.routing.*
|
||||
import io.ktor.util.*
|
||||
import java.io.File
|
||||
|
||||
fun Application.configureHTTP() {
|
||||
install(CORS) {
|
||||
allowMethod(HttpMethod.Options)
|
||||
allowMethod(HttpMethod.Get)
|
||||
allowMethod(HttpMethod.Put)
|
||||
allowMethod(HttpMethod.Delete)
|
||||
allowMethod(HttpMethod.Post)
|
||||
allowHeader(HttpHeaders.AccessControlAllowOrigin)
|
||||
allowHeader(HttpHeaders.Accept)
|
||||
allowHeader(HttpHeaders.ContentType)
|
||||
anyHost()
|
||||
allowCredentials = true
|
||||
allowNonSimpleContentTypes = true
|
||||
}
|
||||
}
|
||||
@@ -1,157 +0,0 @@
|
||||
package com.ray650128.pcredive.plugins
|
||||
|
||||
import com.ray650128.pcredive.database.dto.toDto
|
||||
import com.ray650128.pcredive.database.model.MemberRecord
|
||||
import com.ray650128.pcredive.database.model.Record
|
||||
import com.ray650128.pcredive.database.model.RecordData
|
||||
import com.ray650128.pcredive.database.model.UpdateMemberRecord
|
||||
import com.ray650128.pcredive.database.service.MemberRecordService
|
||||
import com.ray650128.pcredive.database.service.MemberService
|
||||
import io.ktor.http.*
|
||||
import io.ktor.serialization.kotlinx.json.*
|
||||
import io.ktor.server.plugins.contentnegotiation.*
|
||||
import io.ktor.server.response.*
|
||||
import io.ktor.server.application.*
|
||||
import io.ktor.server.request.*
|
||||
import io.ktor.server.routing.*
|
||||
import io.ktor.server.util.*
|
||||
import kotlinx.coroutines.coroutineScope
|
||||
import org.litote.kmongo.toId
|
||||
import java.util.*
|
||||
|
||||
fun Application.configureMemberRecordRouting() {
|
||||
routing {
|
||||
options("{...}") {
|
||||
call.respond(HttpStatusCode.OK)
|
||||
}
|
||||
route("/api") {
|
||||
route("/record") { // 查詢所有紀錄
|
||||
get {
|
||||
val calendar = Calendar.getInstance().apply {
|
||||
timeInMillis = System.currentTimeMillis() - (5 * 60 * 60 * 1000) // 由於公連換日為每日早上5:00,因此減去時差
|
||||
}
|
||||
val records = getData(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH))
|
||||
call.respond(HttpStatusCode.OK, records)
|
||||
}
|
||||
post("/{id}") { // 新增成員紀錄
|
||||
val id = call.parameters.getOrFail<String>("id")
|
||||
val record = call.receive<MemberRecord>()
|
||||
val member = MemberService.findById(id) ?: run {
|
||||
call.respond(HttpStatusCode.NotFound)
|
||||
return@post
|
||||
}
|
||||
|
||||
val now = Calendar.getInstance()
|
||||
val startTime = getDayStartLong(now[Calendar.YEAR], now[Calendar.MONTH], now[Calendar.DAY_OF_MONTH])
|
||||
val endTime = getDayEndLong(now[Calendar.YEAR], now[Calendar.MONTH], now[Calendar.DAY_OF_MONTH])
|
||||
val existData = MemberRecordService.findByMemberIdBetweenDate(id, startTime, endTime) ?: run {
|
||||
record.apply {
|
||||
memberId = member._id
|
||||
createdAt = System.currentTimeMillis()
|
||||
updatedAt = System.currentTimeMillis()
|
||||
}
|
||||
MemberRecordService.create(record).let {
|
||||
call.respond(HttpStatusCode.OK, record)
|
||||
}
|
||||
return@post
|
||||
}
|
||||
existData.apply {
|
||||
memberId = member._id
|
||||
record1 = record.record1
|
||||
record1c = record.record1c
|
||||
record2 = record.record2
|
||||
record2c = record.record2c
|
||||
record3 = record.record3
|
||||
record3c = record.record3c
|
||||
updatedAt = System.currentTimeMillis()
|
||||
}
|
||||
MemberRecordService.updateById(existData._id.toString(), existData).let {
|
||||
call.respond(HttpStatusCode.OK, existData)
|
||||
}
|
||||
}
|
||||
get("/{year}/{month}/{day}") { // 取得特定日期
|
||||
val year = call.parameters.getOrFail<Int>("year").toInt()
|
||||
val month = call.parameters.getOrFail<Int>("month").toInt() - 1
|
||||
val day = call.parameters.getOrFail<Int>("day").toInt()
|
||||
val records = getData(year, month, day)
|
||||
call.respond(HttpStatusCode.OK, records)
|
||||
}
|
||||
get("/{id}") {
|
||||
// Show an article with a specific id
|
||||
val id = call.parameters.getOrFail<String>("id")
|
||||
val record = MemberRecordService.findById(id)?.toDto() ?: run {
|
||||
call.respond(HttpStatusCode.NotFound)
|
||||
return@get
|
||||
}
|
||||
call.respond(HttpStatusCode.OK, record)
|
||||
}
|
||||
put("/{id}") {
|
||||
val id = call.parameters.getOrFail<String>("id")
|
||||
val record = call.receive<UpdateMemberRecord>()
|
||||
val oldData = MemberRecordService.findById(id) ?: run {
|
||||
call.respond(HttpStatusCode.NotFound)
|
||||
return@put
|
||||
}
|
||||
oldData.apply {
|
||||
record1 = record.record1
|
||||
record1c = record.record1c
|
||||
record2 = record.record2
|
||||
record2c = record.record2c
|
||||
record3 = record.record3
|
||||
record3c = record.record3c
|
||||
updatedAt = System.currentTimeMillis()
|
||||
}
|
||||
MemberRecordService.updateById(id, oldData)
|
||||
call.respond(HttpStatusCode.OK, record)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun getDayStartLong(year: Int, month: Int, day: Int): Long {
|
||||
val calendar = Calendar.getInstance().apply {
|
||||
set(Calendar.YEAR, year)
|
||||
set(Calendar.MONTH, month)
|
||||
set(Calendar.DAY_OF_MONTH, day)
|
||||
}
|
||||
return calendar.apply {
|
||||
set(Calendar.HOUR_OF_DAY, 5)
|
||||
set(Calendar.MINUTE, 0)
|
||||
set(Calendar.SECOND, 0)
|
||||
set(Calendar.MILLISECOND, 0)
|
||||
}.timeInMillis
|
||||
}
|
||||
|
||||
fun getDayEndLong(year: Int, month: Int, day: Int): Long {
|
||||
val startTime = getDayStartLong(year, month, day)
|
||||
return startTime + 86399000L
|
||||
}
|
||||
|
||||
fun getData(year: Int, month: Int, day: Int): List<RecordData> {
|
||||
val startTime = getDayStartLong(year, month, day)
|
||||
val endTime = getDayEndLong(year, month, day)
|
||||
val records = ArrayList<RecordData>()
|
||||
val memberList = MemberService.findAll()
|
||||
memberList.forEach { member ->
|
||||
if (member.leave && member.updatedAt!! < startTime) {
|
||||
//println("成員離開 ${member.nickName}")
|
||||
return@forEach
|
||||
}
|
||||
if (member.createAt!! > startTime) {
|
||||
//println("成員不在當期開戰期間 ${member.nickName}")
|
||||
return@forEach
|
||||
}
|
||||
records.add(
|
||||
RecordData(member = member, null)
|
||||
)
|
||||
}
|
||||
val recordList = MemberRecordService.findByTimeBetween(startTime, endTime)
|
||||
recordList.forEach { record ->
|
||||
val player = MemberService.findById(record.memberId.toString())
|
||||
records.firstOrNull { it.member == player }?.let { playerRecord ->
|
||||
playerRecord.record = record
|
||||
}
|
||||
}
|
||||
return records
|
||||
}
|
||||
@@ -1,74 +0,0 @@
|
||||
package com.ray650128.pcredive.plugins
|
||||
|
||||
import com.ray650128.pcredive.database.model.Member
|
||||
import com.ray650128.pcredive.database.service.MemberService
|
||||
import io.ktor.http.*
|
||||
import io.ktor.server.application.*
|
||||
import io.ktor.server.request.*
|
||||
import io.ktor.server.response.*
|
||||
import io.ktor.server.routing.*
|
||||
import io.ktor.server.util.*
|
||||
import kotlinx.coroutines.coroutineScope
|
||||
|
||||
fun Application.configureMemberRouting() {
|
||||
routing {
|
||||
options("{...}") {
|
||||
call.respond(HttpStatusCode.OK)
|
||||
}
|
||||
route("/api") {
|
||||
route("/member") {
|
||||
get {
|
||||
// 顯示所有登錄的成員資料
|
||||
coroutineScope {
|
||||
val memberList = MemberService.findAll()
|
||||
call.respond(HttpStatusCode.OK, memberList)
|
||||
}
|
||||
}
|
||||
get("/{id}") {
|
||||
val id = call.parameters.getOrFail<String>("id")
|
||||
val member = MemberService.findById(id) ?: run {
|
||||
call.respond(HttpStatusCode.NotFound)
|
||||
return@get
|
||||
}
|
||||
call.respond(HttpStatusCode.OK, member)
|
||||
}
|
||||
post {
|
||||
val member = call.receive<Member>()
|
||||
member.apply {
|
||||
createAt = System.currentTimeMillis()
|
||||
updatedAt = System.currentTimeMillis()
|
||||
}
|
||||
MemberService.create(member).let {
|
||||
call.respond(HttpStatusCode.OK, member)
|
||||
}
|
||||
}
|
||||
put("/{id}") {
|
||||
val id = call.parameters.getOrFail<String>("id")
|
||||
val member = call.receive<Member>()
|
||||
val oldData = MemberService.findById(id) ?: run {
|
||||
call.respond(HttpStatusCode.NotFound)
|
||||
return@put
|
||||
}
|
||||
oldData.apply {
|
||||
playerName = member.playerName
|
||||
nickName = member.nickName
|
||||
discordID = member.discordID
|
||||
uid = member.uid
|
||||
leave = member.leave
|
||||
updatedAt = System.currentTimeMillis()
|
||||
}
|
||||
MemberService.updateById(id, oldData)
|
||||
call.respond(HttpStatusCode.OK, oldData)
|
||||
}
|
||||
delete("/{id}") {
|
||||
val id = call.parameters.getOrFail<String>("id")
|
||||
if (MemberService.deleteById(id)) {
|
||||
call.respond(HttpStatusCode.OK)
|
||||
} else {
|
||||
call.respond(HttpStatusCode.NotFound)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,17 +0,0 @@
|
||||
package com.ray650128.pcredive.plugins
|
||||
|
||||
import io.ktor.serialization.kotlinx.json.*
|
||||
import io.ktor.server.plugins.contentnegotiation.*
|
||||
import io.ktor.server.response.*
|
||||
import io.ktor.server.application.*
|
||||
import io.ktor.server.routing.*
|
||||
import kotlinx.serialization.json.Json
|
||||
import org.litote.kmongo.id.serialization.IdKotlinXSerializationModule
|
||||
|
||||
fun Application.configureSerialization() {
|
||||
install(ContentNegotiation) {
|
||||
json(
|
||||
Json { serializersModule = IdKotlinXSerializationModule }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
package com.ray650128.pcredive.plugins
|
||||
|
||||
import com.ray650128.pcredive.database.model.MemberRecord
|
||||
import com.ray650128.pcredive.database.model.Record
|
||||
import com.ray650128.pcredive.database.service.MemberRecordService
|
||||
import com.ray650128.pcredive.database.service.MemberService
|
||||
import io.ktor.server.application.*
|
||||
import java.util.*
|
||||
|
||||
fun Application.configureUpdateTimer() {
|
||||
val date = Date()
|
||||
val timer = Timer()
|
||||
timer.schedule(object : TimerTask() {
|
||||
override fun run() {
|
||||
val c = Calendar.getInstance()
|
||||
val hour = c[Calendar.HOUR_OF_DAY]
|
||||
val minute = c[Calendar.MINUTE]
|
||||
val second = c[Calendar.SECOND]
|
||||
val day = c[Calendar.DAY_OF_MONTH]
|
||||
val lastDay = c.getActualMaximum(Calendar.DAY_OF_MONTH)
|
||||
//println("Time: $day, ${String.format("%2d:%2d:%2d", hour, minute, second)}")
|
||||
if ((day in (lastDay - 5)..lastDay) && (hour == 5 && minute == 0 && second == 0)) {
|
||||
val members = MemberService.findAll(false)
|
||||
members.forEach { member ->
|
||||
MemberRecordService.create(
|
||||
MemberRecord(
|
||||
memberId = member._id,
|
||||
record1 = Record(""),
|
||||
record1c = Record(""),
|
||||
record2 = Record(""),
|
||||
record2c = Record(""),
|
||||
record3 = Record(""),
|
||||
record3c = Record(""),
|
||||
createdAt = System.currentTimeMillis(),
|
||||
updatedAt = System.currentTimeMillis()
|
||||
)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}, date, 1000L)
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
ktor {
|
||||
deployment {
|
||||
port = 10001
|
||||
port = ${?PORT}
|
||||
}
|
||||
application {
|
||||
modules = [ com.ray650128.pcredive.ApplicationKt.module ]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
ktor:
|
||||
deployment:
|
||||
port: 8080
|
||||
application:
|
||||
modules:
|
||||
- club.sakunadaisuki.pcrediveclanrecordbackend.plugins.HttpKt.configureHttp
|
||||
- club.sakunadaisuki.pcrediveclanrecordbackend.plugins.SerializationKt.configureSerialization
|
||||
- club.sakunadaisuki.pcrediveclanrecordbackend.plugins.MongoKt.configureMongo
|
||||
- club.sakunadaisuki.pcrediveclanrecordbackend.plugins.RoutingKt.configureRouting
|
||||
@@ -0,0 +1,23 @@
|
||||
openapi: "3.0.3"
|
||||
info:
|
||||
title: "Application API"
|
||||
description: "Application API"
|
||||
version: "1.0.0"
|
||||
servers:
|
||||
- url: "http://0.0.0.0:8080"
|
||||
paths:
|
||||
/:
|
||||
get:
|
||||
description: "Hello World!"
|
||||
responses:
|
||||
"200":
|
||||
description: "OK"
|
||||
content:
|
||||
text/plain:
|
||||
schema:
|
||||
type: "string"
|
||||
examples:
|
||||
Example#1:
|
||||
value: "Hello World!"
|
||||
components:
|
||||
schemas: { }
|
||||
@@ -4,9 +4,9 @@
|
||||
<pattern>%d{YYYY-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
<root level="trace">
|
||||
<root level="INFO">
|
||||
<appender-ref ref="STDOUT"/>
|
||||
</root>
|
||||
<logger name="org.eclipse.jetty" level="INFO"/>
|
||||
<logger name="io.netty" level="INFO"/>
|
||||
</configuration>
|
||||
</configuration>
|
||||
Reference in New Issue
Block a user