Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Add cleanRelatedContacts service #1019

Merged
merged 1 commit into from
Nov 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions manifest.webapp
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,11 @@
"file": "services/autoDefineLabels/contacts.js",
"trigger": "@event io.cozy.contacts:CREATED,UPDATED",
"debounce": "5s"
},
"cleanRelatedContacts": {
"type": "node",
"file": "services/cleanRelatedContacts/contacts.js",
"trigger": "@event io.cozy.contacts:DELETED"
}
}
}
55 changes: 55 additions & 0 deletions src/helpers/cleanRelatedContactsService.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { Q } from 'cozy-client'
import {
getHasManyItem,
removeHasManyItem
} from 'cozy-client/dist/associations/HasMany'
import logger from 'cozy-logger'

import { DOCTYPE_CONTACTS } from '../helpers/doctypes'

const log = logger.namespace('service/cleanRelatedContactsService')
export const cleanRelatedContactsService = async (client, contactDeletedId) => {
// FIXME: Must be changed when completing the contact relationship functionality.
const allContacts = await client.queryAll(
Q(DOCTYPE_CONTACTS)
.where({
relationships: {
related: {
data: {
$elemMatch: {
_id: contactDeletedId,
_type: DOCTYPE_CONTACTS
Copy link
Contributor

@paultranvan paultranvan Nov 13, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This elemMatch operator is to avoid when possible, because it will force an index full scan.
But why not simply use the include dsl ?

Q(DOCTYPE_CONTACTS).include('related')
``

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

On afterthought, using this query will also make a full-scan, and then query all the the relationships, so not good either...

}
}
}
}
})
.indexFields(['relationships.related.data'])
.limitBy(1000)
)
log('info', `all contacts fetched, ${allContacts.length} contact(s) found`)

if (allContacts?.length > 0) {
const contactsWithRelatedRelDeleted = allContacts.filter(
contact =>
getHasManyItem(contact, 'related', contactDeletedId) !== undefined
)

log(
'info',
`contact ids with related relationships deleted ${contactsWithRelatedRelDeleted
.map(contact => contact._id)
.join(', ')}`
)

if (contactsWithRelatedRelDeleted.length > 0) {
log('info', 'updating contacts with related contact deleted')
const allContactsUpdated = contactsWithRelatedRelDeleted.map(contact =>
removeHasManyItem(contact, 'related', contactDeletedId)
)

log('info', 'saving all contacts updated')
await client.saveAll(allContactsUpdated)
}
}
}
Merkur39 marked this conversation as resolved.
Show resolved Hide resolved
117 changes: 117 additions & 0 deletions src/helpers/cleanRelatedService.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
import { waitFor } from '@testing-library/react'

import { cleanRelatedContactsService } from './cleanRelatedContactsService'

jest.mock('cozy-client', () => ({
Q: jest.fn(() => ({
where: jest.fn(() => ({
indexFields: jest.fn(() => ({
limitBy: jest.fn()
}))
}))
}))
}))

const setup = ({
mockQueryAll = jest.fn(),
mockSaveAll = jest.fn(),
contacts = []
} = {}) => {
const mockClient = {
queryAll: mockQueryAll.mockResolvedValue(contacts),
saveAll: mockSaveAll
}

return mockClient
}

describe('cleanRelatedContactsService', () => {
it('should update contacts with related contact deleted', async () => {
const mockSaveAll = jest.fn()
const contacts = [
{
_id: 'contact0',
relationships: {
related: { data: [{ _id: 'contactDeletedId' }] }
}
},
{
_id: 'contact1',
relationships: {
related: { data: [] }
}
}
]
const client = setup({ mockSaveAll, contacts })

await cleanRelatedContactsService(client, 'contactDeletedId')

await waitFor(() => {
expect(mockSaveAll).toHaveBeenCalledWith([
{
_id: 'contact0',
relationships: {
related: { data: [] }
}
}
])
})
})

it('should update contacts with related contact deleted and keep other relations', async () => {
const mockSaveAll = jest.fn()
const contacts = [
{
_id: 'contact0',
relationships: {
related: { data: [{ _id: 'contactDeletedId' }, { _id: 'OtherId' }] }
}
},
{
_id: 'contact1',
relationships: {
related: { data: [] }
}
}
]
const client = setup({ mockSaveAll, contacts })

await cleanRelatedContactsService(client, 'contactDeletedId')

await waitFor(() => {
expect(mockSaveAll).toHaveBeenCalledWith([
{
_id: 'contact0',
relationships: {
related: { data: [{ _id: 'OtherId' }] }
}
}
])
})
})
Merkur39 marked this conversation as resolved.
Show resolved Hide resolved

it('should not update contacts if no related contact deleted', async () => {
const mockSaveAll = jest.fn()
const contacts = [
{
_id: 'contact0',
relationships: {
related: { data: [{ _id: 'otherId' }] }
}
},
{
_id: 'contact1',
relationships: {
related: { data: [] }
}
}
]
const client = setup({ mockSaveAll, contacts })

await cleanRelatedContactsService(client, 'contactDeletedId')

await waitFor(() => {
expect(mockSaveAll).not.toHaveBeenCalled()
})
})
})
26 changes: 26 additions & 0 deletions src/targets/services/cleanRelatedContacts.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import fetch from 'node-fetch'
import { cleanRelatedContactsService } from 'src/helpers/cleanRelatedContactsService'

import CozyClient from 'cozy-client'
import logger from 'cozy-logger'

import { schema } from '../../helpers/doctypes'

const log = logger.namespace('services/cleanRelatedContacts')

global.fetch = fetch

const cleanRelatedContacts = async () => {
log('info', 'Start cleanRelatedContacts service')
const client = CozyClient.fromEnv(process.env, { schema })
const contactDeleted = JSON.parse(process.env.COZY_COUCH_DOC)
zatteo marked this conversation as resolved.
Show resolved Hide resolved

await cleanRelatedContactsService(client, contactDeleted._id)

log('info', 'All contacts successfully updated')
}

cleanRelatedContacts().catch(e => {
log('error', e)
process.exit(1)
})
Loading