Last active
March 29, 2022 18:15
-
-
Save dmost714/63d69006edd884bf16ba912404766737 to your computer and use it in GitHub Desktop.
Build a GQL filter to get contacts having any of the passed in tags.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const axios = require('axios') | |
const gql = require('graphql-tag') | |
const graphql = require('graphql') | |
const { print } = graphql | |
const listContacts = /* GraphQL */ ` | |
query ListContacts( | |
$filter: ModelContactFilterInput | |
$limit: Int | |
$nextToken: String | |
) { | |
listContacts(filter: $filter, limit: $limit, nextToken: $nextToken) { | |
items { | |
id | |
groups | |
dncEmail | |
ccid | |
name | |
tags | |
metadata | |
createdAt | |
updatedAt | |
} | |
nextToken | |
} | |
} | |
` | |
const buildFilter = (theOrTags, group) => { | |
const orTags = [...theOrTags] | |
let filter = { | |
not: { dncEmail: { size: { gt: 0 } } }, | |
} | |
if (group) { | |
filter.groups = { eq: group } | |
} | |
const tagsFilter = orTags.length === 0 ? {} : | |
orTags.length === 1 ? { | |
tags: { | |
contains: orTags[0] | |
} | |
} : { | |
or: orTags.map(tag => ({ | |
tags: { | |
contains: tag | |
} | |
})) | |
} | |
return { ...filter, ...tagsFilter } | |
} | |
const listContactsWithTags = async (orTags, authorization, group) => { | |
let filter = buildFilter(orTags, group) | |
let variables = { | |
filter, | |
limit: 1000, | |
} | |
//console.log(`variables`, JSON.stringify(variables, null, 2)) | |
let contacts = [] | |
let nextToken = null | |
try { | |
do { | |
variables.nextToken = nextToken | |
const params = { | |
url: process.env.API_XXXX_GRAPHQLAPIENDPOINTOUTPUT, | |
method: 'post', | |
headers: {}, | |
data: { | |
query: print(gql(listContacts)), | |
variables | |
} | |
} | |
if (('cron' === authorization) && group) { | |
params.headers['x-api-key'] = process.env.API_XXXX_GRAPHQLAPIKEYOUTPUT | |
} else if (authorization) { | |
params.headers.authorization = authorization | |
} else throw new Error('You shall not pass') | |
const graphQLData = await axios(params) | |
//console.log('graphQLData.data.data', graphQLData.data.data) | |
graphQLData.data.errors && console.log("listContacts ERRORS:", graphQLData.data.errors) | |
contacts = [...contacts, ...graphQLData.data.data.listContacts.items] | |
//console.log(`Got ${graphQLData.data.data.listContacts.items.length} contacts`) | |
nextToken = graphQLData.data.data.listContacts.nextToken | |
} while (nextToken) | |
} catch (err) { | |
console.log('error getting listContacts items: ', err) | |
contacts = [] | |
} | |
//console.log(`contacts`, contacts) | |
return contacts | |
} | |
module.exports = { | |
listContactsWithTags | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment