Skip to content

Instantly share code, notes, and snippets.

@saroar
Created January 22, 2024 19:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saroar/a006d91814dc3429dc59a5fb059eb2d8 to your computer and use it in GitHub Desktop.
Save saroar/a006d91814dc3429dc59a5fb059eb2d8 to your computer and use it in GitHub Desktop.
public func swapsHandler(
request: Request,
route: SwapsRoute
) async throws -> AsyncResponseEncodable {
switch route {
case .create(input: let input):
if request.loggedIn == false { throw Abort(.unauthorized) }
let ownerID = request.payload.user._id
let title = input.name
let currentDateC = Date.now
var conversation = ConversationModel(
_id: ObjectId(),
title: title,
type: .group,
admins: [ownerID],
members: [ownerID]
)
conversation.createdAt = currentDateC
conversation.updatedAt = currentDateC
let conversationCreate = try await ConversationModel.query(request)
.insertEncoded(conversation)
.insertCount
if conversationCreate < 1 {
throw Abort(.notAcceptable, reason: "Conversation Create Failed")
}
let currentDateS = Date.now
var swapModel = SwapModel(
_id: .init(),
title: title,
addressName: input.addressName,
geometry: Geometry(type: input.type, coordinates: input.coordinates),
ownerId: ownerID,
conversationsId: conversation._id,
categoryId: input.categoryId,
urlString: ""
)
swapModel.createdAt = currentDateS
swapModel.updatedAt = currentDateS
guard let currentUser = try await UserModel
.query(request)
.findOne("_id" == ownerID, as: UserModel.self)
else {
throw Abort(.notFound, reason: "Cant find admin user from id: \(ownerID)")
}
let currentUserAttachments = try await AttachmentModel
.query(request)
.find("userId" == ownerID)
.decode(AttachmentModel.self)
.drain()
let currentAttachmentOutputs = currentUserAttachments.map { $0.mapGet() }
do {
try await SwapModel
.query(request)
.insertEncoded(swapModel)
} catch {
throw Abort(.notAcceptable, reason: "Create SwapModel failed \(error)")
}
return swapModel.mapGet(
attachments: currentAttachmentOutputs,
userOutput: currentUser.mapGetPublic()
)
--------------------------------------
import Vapor
import MongoKitten
import LPGSharedModels
extension SwapPage: Content {}
extension SwapModel: Content {}
extension SwapModel {
public func toBSON() throws -> Document {
let encoder = BSONEncoder()
let bson = try encoder.encode(self)
return bson
}
}
extension SwapModel {
static func query(_ request: Request) -> MongoCollection {
return request.application.mongoDB[Self.collectionName]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment