Finding grandparents in Vapor

Viewed 54

I am currently using Vapor for a database and have run into a roadblock I could use some help with.

I currently have a Business object, which has [AccessPoint] children. Each AccessPoint, itself has a number of [AccessPointContactMethod].

An AccessPointContactMethod can reference its parent AccessPoint by inspecting its accessPointID property which is set by Vapor when creating a parent child relationship.

In fact, I use this to make sure that when a new AccessPointContactMethod is created, if the parent AccessPoint already has a child with the same address, we abort the post request:

return AccessPointContactMethod.query(on: req).group(.and) { and in
            and.filter(\.contactMethodAddress == contactMethod.contactMethodAddress)
            and.filter(\.accessPointID == contactMethod.accessPointID)
            }.all()
            .flatMap(to: AccessPointContactMethod.self) { methods in
                if methods.isEmpty {
                    return contactMethod.save(on: req)
                }
                else {
                    let duplicateContactMethodStatus = HTTPResponseStatus.custom(code: 600, reasonPhrase: "Duplicate Contact Method")
                    throw Abort(duplicateContactMethodStatus)
                }
        }

So this leads me to the problem I'm having. At the moment, I only check if there are duplicate addresses in that one AccessPoint, but what I want to do is check all the AccessPoint objects belonging to the one Business, and if there is any AccessPoint that contains an AccessPointContactMethod with the same address, then we abort the request.

Therefore, it seems to me, that I need a way of getting to the Business grandparent object and iterating over the [AccessPoint] children for any duplicates.

Vapor, reactive programming, databases are all quite new to me, so I'm sure I haven't described this question wonderfully but if anyone can understand what I'm trying to do and has any ideas, I'd be highly appreciative!

0 Answers
Related