diff --git a/__tests__/requests/insee.spec.js b/__tests__/requests/insee.spec.js index f8b82a568521478f1b328c10c8546040ab82d8ce..10906459481d629fcaa93701dd1cdeddfbf67d6f 100644 --- a/__tests__/requests/insee.spec.js +++ b/__tests__/requests/insee.spec.js @@ -184,5 +184,19 @@ describe('getInseeCode', () => { expect(await getInseeCode(95640, 'Breancon')).toEqual('95102') }) }) + + describe('should return correct insee code when other communes contains the city', () => { + it('should return insee code for: Cluses', async () => { + expect(await getInseeCode(74300, 'Cluses')).toEqual('74081') + }) + it('should return insee code for: Chatillon sur cluses', async () => { + expect(await getInseeCode(74300, 'Chatillon sur cluses')).toEqual( + '74064' + ) + }) + it('should return insee code for: Nancy sur cluses', async () => { + expect(await getInseeCode(74300, 'Nancy sur cluses')).toEqual('74196') + }) + }) }) }) diff --git a/src/requests/insee.js b/src/requests/insee.js index 10cb96e41d02e91b9d1b38f114b8c5e160d6a378..adf9236a4a769c3cd46cca905fadb00790096b6d 100644 --- a/src/requests/insee.js +++ b/src/requests/insee.js @@ -27,13 +27,20 @@ async function getInseeCode(postalCode, city) { sanitizeCity(commune.nomCommune).includes(parsedCity) ) + if (filteredResponse.length === 1) { + return filteredResponse[0].codeCommune + } + if (filteredResponse.length > 1) { - throw new Error( - 'Input city is not precise enough, more than one city was found' - ) + // Try to get the same length of the city input + for (const commune of filteredResponse) { + if (commune.nomCommune.length === city.length) { + return commune.codeCommune + } + } } - return filteredResponse[0].codeCommune + throw new Error('No match could be found') } } catch (error) { const errorMessage = `Query getInseeCode failed for postalCode ${postalCode} / ${city}`