import { DB_TIMEOUT , ErrorMessage } from '@celo/phone-number-privacy-common' ; import Logger from 'bunyan' ; import { getDatabase } from '../database' ; import { NUMBER_PAIRS_COLUMN , NUMBER_PAIRS_TABLE , NumberPair } from '../models/numberPair' ; function numberPairs ( ) { return getDatabase ( ) < NumberPair > ( NUMBER_PAIRS_TABLE ) ; } export async function getNumberPairContacts ( userPhone , contactPhones , logger ) { try { const contentPairs = await numberPairs ( ) . select ( NUMBER_PAIRS_COLUMN . userPhoneHash ) . where ( NUMBER_PAIRS_COLUMN . contactPhoneHash , userPhone ) . timeout ( DB_TIMEOUT ) ; const contactPhonesSet = new Set ( contactPhones ) ; return contentPairs . map ( ( contactPair ) => contactPair [ NUMBER_PAIRS_COLUMN . userPhoneHash ] ) . filter ( ( number ) => contactPhonesSet . has ( number ) ) ; } catch ( err ) { logger . error ( ErrorMessage . DATABASE_GET_FAILURE ) ; logger . error ( err ) ; return [ ] ; } } export async function setNumberPairContacts ( userPhone , contactPhones , logger ) { const rows = [ ] ; for ( const contactPhone of contactPhones ) { const data = new NumberPair ( userPhone , contactPhone ) ; rows . push ( data ) ; } try { await getDatabase ( ) . batchInsert ( NUMBER_PAIRS_TABLE , rows ) ; } catch ( err ) { if ( err . code !== '23505' ) { logger . error ( ErrorMessage . DATABASE_INSERT_FAILURE ) ; logger . error ( err ) ; } } }