Last active
November 15, 2020 17:13
-
-
Save saroar/faf8132c949047ed0d3384db922adc00 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
func create(_ req: Request) throws -> EventLoopFuture<[Contact.ReqRes]> { | |
if req.loggedIn == false { throw Abort(.unauthorized) } | |
let inputData = try req.content.decode([Contact.ReqRes].self) | |
return Contact.query(on: req.db).filter(\.$user.$id == req.payload.userId).all().flatMap { contactsRes in | |
let contacts = contactsRes.map { $0.response } | |
let setOriginal = Set(inputData) | |
let setServerContacts = Set(contacts) | |
let uniqServer = setOriginal.subtracting(setServerContacts) | |
let uniqOrg = setServerContacts.subtracting(setOriginal) | |
if uniqServer.isEmpty && uniqOrg.isEmpty { | |
let contsss = Contact.query(on: req.db) | |
.filter(\.$user.$id == req.payload.userId) | |
.filter(\.$isRegister == true) | |
.all() | |
.map { uniqContacts in | |
return uniqContacts.map { cc in | |
return cc.response | |
} | |
} | |
return contsss | |
} | |
let newContacts = uniqServer.isEmpty ? uniqOrg : uniqServer | |
let results = newContacts.compactMap { (contact: Contact.ReqRes) -> EventLoopFuture<Contact.ReqRes> in | |
return User.query(on: req.db) | |
.filter(\.$phoneNumber == contact.phoneNumber) | |
.all() | |
.flatMap { users -> EventLoopFuture<Contact.ReqRes> in | |
let user = users.first == nil ? User(phoneNumber: "") : users.first! | |
let contact = Contact( | |
phoneNumber: contact.phoneNumber, | |
identifier: contact.identifier ?? "", | |
fullName: contact.fullName, | |
avatar: user.avatar, | |
isRegister: user.phoneNumber == contact.phoneNumber, | |
userId: contact.userId | |
) | |
return contact.save(on: req.db).transform(to: contact.response) //.map { _ in contact } | |
} | |
} | |
return results.flatten(on: req.eventLoop) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment