@@ -52,7 +52,6 @@ router.get('/:entity_id', async (req, res) => {
5252router . post ( '/' , async ( req , res ) => {
5353 let code ;
5454 let message ;
55- let ec ;
5655 try {
5756 if ( req . body . name !== undefined ) {
5857 let { name, address, phone, email, checkIn, contacts } = req . body ;
@@ -69,7 +68,7 @@ router.post('/', async (req, res) => {
6968 const entity = await req . context . models . Entity . create ( { name, address, email, phone, checkIn } ) ;
7069 if ( contacts ) {
7170 for ( const contact of contacts ) {
72- ec = {
71+ const ec = {
7372 entityId : entity . id ,
7473 contactId : contact . id
7574 }
@@ -97,7 +96,6 @@ router.post('/', async (req, res) => {
9796router . put ( '/' , async ( req , res ) => {
9897 let code ;
9998 let message ;
100- let ec ;
10199 try {
102100 if ( validator . isUUID ( req . body . id ) ) {
103101 let { id, name, address, phone, email, checkIn, contacts } = req . body ;
@@ -218,8 +216,6 @@ router.post('/link/:entity_id', async (req, res) => {
218216 }
219217 } ) ;
220218
221-
222-
223219 const ec = {
224220 entityId : entity . id ,
225221 contactId : contactToLink . id
@@ -231,7 +227,7 @@ router.post('/link/:entity_id', async (req, res) => {
231227
232228 await req . context . models . EntityContact . createIfNew ( ec ) ;
233229 }
234- message = `Link successful/already exists for entity with ID ${ entity . id } ` ;
230+ message = `Linking successful/already exists for entity with ID ${ entity . id } ` ;
235231 code = 200 ;
236232 } else {
237233 code = 422 ;
@@ -244,4 +240,46 @@ router.post('/link/:entity_id', async (req, res) => {
244240 return utils . response ( res , code , message ) ;
245241} ) ;
246242
243+ // unlinks entity with list of contacts
244+ router . post ( '/unlink/:entity_id' , async ( req , res ) => {
245+ let code ;
246+ let message ;
247+ try {
248+ if ( validator . isUUID ( req . params . entity_id ) ) {
249+ const entity = await req . context . models . Entity . findOne ( {
250+ where : {
251+ id : req . params . entity_id
252+ }
253+ } ) ;
254+
255+ for ( const contact of req . body . contacts ) {
256+ const contactToUnLink = await req . context . models . Contact . findOne ( {
257+ where : {
258+ id : contact . id
259+ }
260+ } ) ;
261+
262+ // ideally only one of these should exist
263+ const ec = await req . context . models . EntityContact . findOne ( {
264+ where : {
265+ entityId : entity . id ,
266+ contactId : contactToUnLink . id
267+ }
268+ } ) ;
269+
270+ await ec . destroy ( ) ;
271+ }
272+ message = `Unlinking successful for entity with ID ${ entity . id } ` ;
273+ code = 200 ;
274+ } else {
275+ code = 422 ;
276+ }
277+ } catch ( e ) {
278+ console . error ( e ) ;
279+ code = 500 ;
280+ }
281+
282+ return utils . response ( res , code , message )
283+ } ) ;
284+
247285export default router ;
0 commit comments