This repository has been archived on 2024-12-15. You can view files and clone it, but cannot push or open issues or pull requests.
seepur/app/Utils/UserChildUtils.js

78 lines
2.8 KiB
JavaScript
Raw Normal View History

2020-04-12 14:25:42 +00:00
const Link = use('App/Models/Link');
const Child = use('App/Models/Child');
2020-04-12 14:25:42 +00:00
class UserChildUtils {
static async isUserConnectedToChild(user_id, child_id) {
const links = await Link.query().where({ user_id, child_id }).fetch();
return !!links.rows.length;
}
static async isParentOf(user_id, child_id) {
const links =
await Link.query().where({ user_id, child_id, is_parent: true }).fetch();
return !!links.rows.length;
}
2020-04-12 14:25:42 +00:00
static async getChildParents(child_id) {
const links = await Link.query().where({ child_id, is_parent: true }).fetch();
const parents = await Promise.all(links.rows.map(async l => {
return l.user().fetch();
}));
return parents;
}
static async getUserConnections(user_id) {
const links = await Link.query().where({ user_id }).fetch();
const connections = await links.rows.reduce(async(_prev, link) => {
const prev = await _prev;
const is_parent = link.is_parent;
const child = await link.child().fetch();
if (is_parent) {
const parents = await UserChildUtils.getChildParents(child.id);
const nonSameUserParents = parents.filter(p => p.id != user_id);
prev.children.push({
...child.toJSON(),
connections: [
...await UserChildUtils.getChildConnections(child.id),
...nonSameUserParents
]
})
} else {
prev.connections.push({
...child.toJSON(),
connections: [...await UserChildUtils.getChildParents(child.id)]
})
}
return prev;
}, Promise.resolve({ children: [], connections: [] }));
return connections;
}
2020-04-12 14:25:42 +00:00
static async getChildConnections(child_id) {
const links =
await Link.query().where({ child_id, is_parent: false }).fetch();
const connections = await Promise.all(links.rows.map(async l => {
return l.user().fetch();
}));
return connections;
}
static async addConnection(child_id, user_id, is_parent = false) {
const link = await Link.create({ child_id, user_id, is_parent });
const user = await link.user().fetch();
const child = await link.child().fetch();
return {
user,
child,
is_parent
}
}
2020-04-12 14:25:42 +00:00
static async deleteChild(child_id) {
const child = await Child.find(child_id)
const childLinks = await child.links().fetch();
2020-04-12 14:25:42 +00:00
const promises = [...childLinks.rows.map(l => (l.delete())), child.delete()];
return await Promise.all(promises);
2020-04-12 14:25:42 +00:00
}
}
module.exports = UserChildUtils;