26 lines
939 B
TypeScript
26 lines
939 B
TypeScript
import Component from '#models/component'
|
|
import Computer from '#models/computer'
|
|
|
|
async function handleComponents(componentsId: number[], computer: Computer) {
|
|
const currentComponents = await computer.related('components').query()
|
|
const currentComponentsIds = currentComponents.map((component) => component.id)
|
|
const componentsToAdd = componentsId.filter((id) => !currentComponentsIds.includes(id))
|
|
const componentsToRemove = currentComponentsIds.filter((id) => !componentsId.includes(id))
|
|
await Promise.all(
|
|
componentsToAdd.map(async (id: number) => {
|
|
const component = await Component.findOrFail(id)
|
|
component.computerId = computer.id
|
|
await component.save()
|
|
})
|
|
)
|
|
await Promise.all(
|
|
componentsToRemove.map(async (id: number) => {
|
|
const component = await Component.findOrFail(id)
|
|
component.computerId = null
|
|
await component.save()
|
|
})
|
|
)
|
|
}
|
|
|
|
export { handleComponents }
|