Created
January 22, 2024 19:40
-
-
Save saroar/a006d91814dc3429dc59a5fb059eb2d8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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