Polarcraft/webv2/server/api/users/[id]/minecraft.put.ts

46 lines
1.2 KiB
TypeScript
Raw Normal View History

import mongoose from 'mongoose'
export default defineEventHandler(async (event) => {
const { code } = await readBody(event)
const userId: string = event.context.params ? event.context.params.id : '@me'
let whitelistDoc
try {
whitelistDoc = await WhitelistModel.findOne({ code })
if (!whitelistDoc) {
throw createError({ statusCode: 500, statusMessage: 'Whitelist document was not found' })
}
} catch (e) {
console.error('Failed to get whitelist document', e)
throw createError('Failed to get whitelist document')
}
const minecraftProfile: any = await $fetch(`https://sessionserver.mojang.com/session/minecraft/profile/${whitelistDoc.uuid}`)
const user = await getUser(userId, event)
const session = await mongoose.startSession()
session.startTransaction()
try {
whitelistDoc.connected = true
user.minecraft = { uuid: whitelistDoc.uuid, username: minecraftProfile.name }
whitelistDoc.save({ session })
user.save({ session })
await session.commitTransaction()
} catch (e) {
console.error('Failed to update documents', e)
await session.abortTransaction()
throw createError('Failed to update documents')
} finally {
session.endSession()
}
return user.minecraft
})