I've built a few functions to table channel & category information, one of which runs when the bot starts to make sure everything is synced.
The problem I've run into is that bot.channels.cache contains channels that no longer exist, or states of a channel that no longer exists. For example, I only have one channel in the server called "general". Yet, there are 3 separate entries for that channel by name, and only one contains the ID (711043006781849686) of the current "general" channel:
import Discord from 'discord.js'
import config from '../config.js'
const bot = new Discord.Client({ partials: ['MESSAGE', 'CHANNEL', 'REACTION'] })
bot.login(config.botToken)
bot.on('ready', async () => {
console.log(bot.channels.cache)
}
-- returns --
Collection(46) [Map] {
...
'711043006781849686' => <ref *16> TextChannel {
type: 'text',
deleted: false,
id: '711043006781849686',
name: 'general',
rawPosition: 10,
parentID: '711043007197216880',
permissionOverwrites: Collection(3) [Map] {
'711043006253367426' => [PermissionOverwrites],
'711043006295179347' => [PermissionOverwrites],
'861109585930747934' => [PermissionOverwrites]
},
topic: 'General chat channel.',
nsfw: false,
lastMessageID: '860794574707752980',
rateLimitPerUser: 0,
lastPinTimestamp: null,
guild: Guild {
members: [GuildMemberManager],
channels: [GuildChannelManager],
roles: [RoleManager],
presences: [PresenceManager],
voiceStates: [VoiceStateManager],
deleted: false,
available: true,
id: '711043006253367426',
shardID: 0,
name: 'Omegabox',
icon: null,
splash: null,
discoverySplash: null,
region: 'us-central',
memberCount: 5,
large: false,
features: [Array],
applicationID: null,
afkTimeout: 900,
afkChannelID: '711043009944223832',
systemChannelID: '711043006781849686',
embedEnabled: undefined,
premiumTier: 0,
premiumSubscriptionCount: 0,
verificationLevel: 'NONE',
explicitContentFilter: 'DISABLED',
mfaLevel: 0,
joinedTimestamp: 1589597389528,
defaultMessageNotifications: 'ALL',
systemChannelFlags: [SystemChannelFlags],
maximumMembers: 100000,
maximumPresences: null,
approximateMemberCount: null,
approximatePresenceCount: null,
vanityURLCode: null,
vanityURLUses: null,
description: null,
banner: null,
rulesChannelID: null,
publicUpdatesChannelID: null,
preferredLocale: 'en-US',
ownerID: '598729034867933195',
emojis: [GuildEmojiManager]
},
messages: MessageManager {
cacheType: [class LimitedCollection extends Collection],
cache: [LimitedCollection [Map]],
channel: [Circular *16]
},
_typing: Map(0) {}
},
...
'827343616678559757' => <ref *33> TextChannel {
type: 'text',
deleted: false,
id: '827343616678559757',
name: 'general',
rawPosition: 0,
parentID: '827343616678559755',
permissionOverwrites: Collection(0) [Map] {},
topic: null,
lastMessageID: '830245759152291860',
rateLimitPerUser: 0,
lastPinTimestamp: null,
guild: Guild {
members: [GuildMemberManager],
channels: [GuildChannelManager],
roles: [RoleManager],
presences: [PresenceManager],
voiceStates: [VoiceStateManager],
deleted: false,
available: true,
id: '827343616678559754',
shardID: 0,
name: 'Megabox Emojis 1',
icon: null,
splash: null,
discoverySplash: null,
region: 'us-west',
memberCount: 3,
large: false,
features: [],
applicationID: null,
afkTimeout: 300,
afkChannelID: null,
systemChannelID: '827343616678559757',
embedEnabled: undefined,
premiumTier: 0,
premiumSubscriptionCount: 0,
verificationLevel: 'NONE',
explicitContentFilter: 'DISABLED',
mfaLevel: 0,
joinedTimestamp: 1617380998194,
defaultMessageNotifications: 'ALL',
systemChannelFlags: [SystemChannelFlags],
maximumMembers: 100000,
maximumPresences: null,
approximateMemberCount: null,
approximatePresenceCount: null,
vanityURLCode: null,
vanityURLUses: null,
description: null,
banner: null,
rulesChannelID: null,
publicUpdatesChannelID: null,
preferredLocale: 'en-US',
ownerID: '598729034867933195',
emojis: [GuildEmojiManager]
},
messages: MessageManager {
cacheType: [class LimitedCollection extends Collection],
cache: [LimitedCollection [Map]],
channel: [Circular *33]
},
nsfw: false,
_typing: Map(0) {}
},
...
'827344454259703842' => <ref *34> TextChannel {
type: 'text',
deleted: false,
id: '827344454259703842',
name: 'general',
rawPosition: 0,
parentID: '827344454259703840',
permissionOverwrites: Collection(0) [Map] {},
topic: null,
lastMessageID: '827580681730261032',
rateLimitPerUser: 0,
lastPinTimestamp: null,
guild: Guild {
members: [GuildMemberManager],
channels: [GuildChannelManager],
roles: [RoleManager],
presences: [PresenceManager],
voiceStates: [VoiceStateManager],
deleted: false,
available: true,
id: '827344454259703838',
shardID: 0,
name: 'Megabox Emojis 2',
icon: null,
splash: null,
discoverySplash: null,
region: 'us-west',
memberCount: 3,
large: false,
features: [],
applicationID: null,
afkTimeout: 300,
afkChannelID: null,
systemChannelID: '827344454259703842',
embedEnabled: undefined,
premiumTier: 0,
premiumSubscriptionCount: 0,
verificationLevel: 'NONE',
explicitContentFilter: 'DISABLED',
mfaLevel: 0,
joinedTimestamp: 1617381010142,
defaultMessageNotifications: 'ALL',
systemChannelFlags: [SystemChannelFlags],
maximumMembers: 100000,
maximumPresences: null,
approximateMemberCount: null,
approximatePresenceCount: null,
vanityURLCode: null,
vanityURLUses: null,
description: null,
banner: null,
rulesChannelID: null,
publicUpdatesChannelID: null,
preferredLocale: 'en-US',
ownerID: '598729034867933195',
emojis: [GuildEmojiManager]
},
messages: MessageManager {
cacheType: [class LimitedCollection extends Collection],
cache: [LimitedCollection [Map]],
channel: [Circular *34]
},
nsfw: false,
_typing: Map(0) {}
}
}
I'm aware that there is a category named "General" (ID: 711043007197216880), but the casing is different which is maintained in an entry. I've filtered that one out, along with everything else that isn't "general" from the above block.
What am I missing here? Possible to sync things up?
Always have an epiphany right after finally making a post.
Been at this for hours and never realized that in this specific call I'm not specifying what guild, or rather what server. The bot is in multiple servers, and I've already got the current server's ID in the config I'm working with.
Changed bot.channels.cache to bot.guilds.cache.get(config.guildId).channels.cache.
Related
I use the NodeJS SDK to authorize the credit card for later capturing and get successful response but with empty refTransId, so I can't capture the transaction.
I wonder why and if the Sandbox environment should return the refTransId?
The request is as follow:
CreateTransactionRequest {
merchantAuthentication: MerchantAuthenticationType {
name: 'xxxxx',
transactionKey: 'xxxxxxxx',
sessionToken: null,
password: null,
impersonationAuthentication: null,
fingerPrint: null,
clientKey: null,
accessToken: null,
mobileDeviceId: null
},
clientId: null,
refId: '2MFSJPT0XC0KJ60NS1P1',
transactionRequest: TransactionRequestType {
transactionType: 'authOnlyTransaction',
amount: 100,
currencyCode: 'USD',
payment: PaymentType {
creditCard: null,
bankAccount: null,
trackData: null,
encryptedTrackData: null,
payPal: null,
opaqueData: [OpaqueDataType],
emv: null,
dataSource: null
},
profile: null,
solution: null,
callId: null,
terminalNumber: null,
authCode: null,
refTransId: null,
splitTenderId: null,
order: OrderType {
invoiceNumber: '82',
description: 'Authorize Client CC',
discountAmount: null,
taxIsAfterDiscount: null,
totalTaxTypeCode: null,
purchaserVATRegistrationNumber: null,
merchantVATRegistrationNumber: null,
vatInvoiceReferenceNumber: null,
purchaserCode: null,
summaryCommodityCode: null,
purchaseOrderDateUTC: null,
supplierOrderReference: null,
authorizedContactName: null,
cardAcceptorRefNumber: null,
amexDataTAA1: null,
amexDataTAA2: null,
amexDataTAA3: null,
amexDataTAA4: null
},
lineItems: ArrayOfLineItem { lineItem: [Array] },
tax: null,
duty: null,
shipping: null,
taxExempt: null,
poNumber: null,
customer: CustomerType {
type: 'individual',
id: '627d08cfc5c631872d9',
email: 'shayzalm234an#gmail.com',
phoneNumber: null,
faxNumber: null,
driversLicense: null,
taxId: null
},
billTo: CustomerAddressType {
firstName: 'adas',
lastName: '',
company: '',
address: 'Southwest 1st Avenue 3298',
city: 'Miami-Dade County',
state: 'Florida',
zip: undefined,
country: 'USA',
phoneNumber: null,
faxNumber: null,
email: null
},
shipTo: null,
customerIP: null,
cardholderAuthentication: null,
retail: null,
employeeId: null,
transactionSettings: null,
userFields: null,
surcharge: null,
merchantDescriptor: null,
subMerchant: null,
tip: null,
processingOptions: null,
subsequentAuthInformation: null,
otherTax: null,
shipFrom: null,
authorizationIndicatorType: null
}
}
The response is as follow:
{
"messages": {
"resultCode": "Ok",
"message": [
{
"code": "I00001",
"text": "Successful."
}
]
},
"transactionResponse": {
"responseCode": "1",
"authCode": "000000",
"avsResultCode": "P",
"cvvResultCode": "",
"cavvResultCode": "",
"transId": "0",
"refTransID": "",
"transHash": "",
"testRequest": "1",
"accountNumber": "XXXX0000",
"accountType": "Visa",
"messages": {
"message": [
{
"code": "1",
"description": "This transaction has been approved."
}
]
},
"transHashSha2": ""
}
This is the documentation reference I use:
https://developer.authorize.net/api/reference/index.html#payment-transactions-authorize-a-credit-card.
I found out that my test account was on test mode and had to be switched to "live" in order to simulate transactions.
I am trying to make my discord bot mass give everyone in my server a role. Whenever I do -giveall it only gives me the role. I have tried using map and array. Using message.guild.members.filter(member => member.roles.array().length > 1).forEach(member => member.addRole(role)); with no luck.
if (command === 'giveall') {
let role = message.guild.roles.cache.find(r => r.name == 'cool')
if (!role) return message.channel.send(`**${message.author.username}**, role not found`)
message.guild.members.cache.filter(m => !m.user.bot).forEach(member => member.roles.add(role))
message.channel.send(`**${message.author.username}**, role **${role.name}** was added to all members`)
}
Here is the log I received with console.log(message.guild.members.cache.filter(m => !m.user.bot));:
Collection [Map] {
'759457326251114536' => GuildMember {
guild: Guild {
members: [GuildMemberManager],
channels: [GuildChannelManager],
roles: [RoleManager],
presences: [PresenceManager],
voiceStates: [VoiceStateManager],
deleted: false,
available: true,
id: '760015259619819550',
shardID: 0,
name: 'GoodGameBTWâ„¢',
icon: '5c364ec985a0706a27c31b89953d01e4',
splash: null,
discoverySplash: null,
region: 'india',
memberCount: 10,
large: false,
features: [Array],
applicationID: null,
afkTimeout: 300,
afkChannelID: null,
systemChannelID: null,
embedEnabled: undefined,
premiumTier: 0,
premiumSubscriptionCount: 0,
verificationLevel: 'LOW',
explicitContentFilter: 'ALL_MEMBERS',
mfaLevel: 0,
joinedTimestamp: 1603042420216,
defaultMessageNotifications: 'MENTIONS',
systemChannelFlags: [SystemChannelFlags],
maximumMembers: 100000,
vanityURLCode: null,
vanityURLUses: null,
description: null,
banner: null,
rulesChannelID: '771729349632196608',
publicUpdatesChannelID: '768502471676788777',
preferredLocale: 'en-US',
ownerID: '759457326251114536',
emojis: [GuildEmojiManager]
},
joinedTimestamp: 1601272158336,
lastMessageID: '773102408938029056',
lastMessageChannelID: '760778837612822558',
premiumSinceTimestamp: 0,
deleted: false,
nickname: null,
_roles: [ '760763514402111488', '760759896232296468' ],
user: User {
id: '759457326251114536',
username: 'Prof. MineKraft',
bot: false,
discriminator: '6612',
avatar: '97ee817e5098d3e6ee4c174a449d1779',
flags: [UserFlags],
lastMessageID: '773102408938029056',
lastMessageChannelID: '760778837612822558'
}
}
}
From the log, you can see that the cache has only two users, the bot and you. So when you filter the bot out, only you get the role.
This can be because you have gateway intents disabled. Please go to the discord developer portal and enable the Server member intent. That should fix your problem.
I am doing stripe subscription using node js Api's when i go to subscription under dashboard its created subscription but it gives status incomplete,no payment deduction occurs
if i am doing through dashboard its create the subscription with active status
id: 'sub_INTyoOKF5bt1ib',
object: 'subscription',
application_fee_percent: null,
billing_cycle_anchor: 1605199862,
billing_thresholds: null,
cancel_at: null,
cancel_at_period_end: false,
canceled_at: null,
collection_method: 'charge_automatically',
created: 1605199862,
current_period_end: 1605286262,
current_period_start: 1605199862,
customer: 'cus_INTyfeuOhg9XDC',
days_until_due: null,
default_payment_method: null,
default_source: null,
default_tax_rates: [],
discount: null,
ended_at: null,
items: {
object: 'list',
data: [ [Object] ],
has_more: false,
total_count: 1,
url: '/v1/subscription_items?subscription=sub_INTyoOKF5bt1ib'
},
latest_invoice: 'in_1Hmj0lLm4uTMGNUSyogmK9TA',
livemode: true,
metadata: {},
next_pending_invoice_item_invoice: null,
pause_collection: null,
pending_invoice_item_interval: null,
pending_setup_intent: null,
pending_update: null,
plan: {
id: 'price_1HlYMvLm4uTMGNUSarJML52T',
object: 'plan',
active: true,
aggregate_usage: null,
amount: 100,
amount_decimal: '100',
billing_scheme: 'per_unit',
created: 1604920625,
currency: 'inr',
interval: 'day',
interval_count: 1,
livemode: true,
metadata: {},
nickname: null,
product: 'prod_IMGu6PI2mJbBCi',
tiers_mode: null,
transform_usage: null,
trial_period_days: null,
usage_type: 'licensed'
},
quantity: 1,
schedule: null,
start_date: 1605199862,
status: 'incomplete',
transfer_data: null,
trial_end: null,
trial_start: null
}
*********latest invoice and payment intent
id: 'sub_INkoNdFnS5DaZR',
object: 'subscription',
application_fee_percent: null,
billing_cycle_anchor: 1605262511,
billing_thresholds: null,
cancel_at: null,
cancel_at_period_end: false,
canceled_at: null,
collection_method: 'charge_automatically',
created: 1605262511,
current_period_end: 1605348911,
current_period_start: 1605262511,
customer: 'cus_INkoPwPjgIyGbV',
days_until_due: null,
default_payment_method: null,
default_source: null,
default_tax_rates: [],
discount: null,
ended_at: null,
items: {
object: 'list',
data: [ [Object] ],
has_more: false,
total_count: 1,
url: '/v1/subscription_items?subscription=sub_INkoNdFnS5DaZR'
},
latest_invoice: {
id: 'in_1HmzJDLm4uTMGNUSmbbqqwR7',
object: 'invoice',
account_country: 'IN',
account_name: 'Walkify',
account_tax_ids: null,
amount_due: 100,
amount_paid: 0,
amount_remaining: 100,
application_fee_amount: null,
attempt_count: 0,
attempted: true,
auto_advance: true,
billing_reason: 'subscription_create',
charge: null,
collection_method: 'charge_automatically',
created: 1605262511,
currency: 'inr',
custom_fields: null,
customer: 'cus_INkoPwPjgIyGbV',
customer_address: {
city: 'Mangaliya,Indore',
country: 'IN',
line1: '',
line2: '',
postal_code: null,
state: 'India'
},
customer_email: 'abc#gmail.com',
customer_name: 'Ravi R',
customer_phone: '',
customer_shipping: null,
customer_tax_exempt: 'none',
customer_tax_ids: [],
default_payment_method: null,
default_source: null,
default_tax_rates: [],
description: null,
discount: null,
discounts: [],
due_date: null,
ending_balance: 0,
footer: null,
hosted_invoice_url: 'https://invoice.stripe.com/i/acct_1HZVL5Lm4uTMGNUS/invst_INkotPj0f800RnPxEA5u8Lzw7IR6Dvy',
invoice_pdf: 'https://pay.stripe.com/invoice/acct_1HZVL5Lm4uTMGNUS/invst_INkotPj0f800RnPxEA5u8Lzw7IR6Dvy/pdf',
last_finalization_error: null,
lines: {
object: 'list',
data: [Array],
has_more: false,
total_count: 1,
url: '/v1/invoices/in_1HmzJDLm4uTMGNUSmbbqqwR7/lines'
},
livemode: true,
metadata: {},
next_payment_attempt: null,
number: 'A77E89AD-0001',
paid: false,
payment_intent: {
id: 'pi_1HmzJDLm4uTMGNUSRu34ggsq',
object: 'payment_intent',
amount: 100,
amount_capturable: 0,
amount_received: 0,
application: null,
application_fee_amount: null,
canceled_at: null,
cancellation_reason: null,
capture_method: 'automatic',
charges: [Object],
client_secret: 'pi_1HmzJDLm4uTMGNUSRu34ggsq_secret_7Sk56e79TEjpt3EQSI4a7CS5a',
confirmation_method: 'automatic',
created: 1605262511,
currency: 'inr',
customer: 'cus_INkoPwPjgIyGbV',
description: 'Subscription creation',
invoice: 'in_1HmzJDLm4uTMGNUSmbbqqwR7',
last_payment_error: null,
livemode: true,
metadata: {},
next_action: [Object],
on_behalf_of: null,
payment_method: 'pm_1HmzJBLm4uTMGNUSeROzE4C9',
payment_method_options: [Object],
payment_method_types: [Array],
receipt_email: null,
review: null,
setup_future_usage: 'off_session',
shipping: null,
source: null,
statement_descriptor: null,
statement_descriptor_suffix: null,
status: 'requires_action',
transfer_data: null,
transfer_group: null
},
period_end: 1605262511,
period_start: 1605262511,
post_payment_credit_notes_amount: 0,
pre_payment_credit_notes_amount: 0,
receipt_number: null,
starting_balance: 0,
statement_descriptor: null,
status: 'open',
status_transitions: {
finalized_at: 1605262511,
marked_uncollectible_at: null,
paid_at: null,
voided_at: null
},
subscription: 'sub_INkoNdFnS5DaZR',
subtotal: 100,
tax: null,
total: 100,
total_discount_amounts: [],
total_tax_amounts: [],
transfer_data: null,
webhooks_delivered_at: 1605262511
},
livemode: true,
metadata: {},
next_pending_invoice_item_invoice: null,
pause_collection: null,
pending_invoice_item_interval: null,
pending_setup_intent: null,
pending_update: null,
plan: {
id: 'price_1HlYMvLm4uTMGNUSarJML52T',
object: 'plan',
active: true,
aggregate_usage: null,
amount: 100,
amount_decimal: '100',
billing_scheme: 'per_unit',
created: 1604920625,
currency: 'inr',
interval: 'day',
interval_count: 1,
livemode: true,
metadata: {},
nickname: null,
product: 'prod_IMGu6PI2mJbBCi',
tiers_mode: null,
transform_usage: null,
trial_period_days: null,
usage_type: 'licensed'
},
quantity: 1,
schedule: null,
start_date: 1605262511,
status: 'incomplete',
transfer_data: null,
trial_end: null,
trial_start: null
}
Stripe account country is india and card is also india
I believe this one is a bug.
I am trying to write a simple web scraper with request and cheerio.
How I tried to solve it:
Yes, I played with other ways to define a selector.
Yes, I have investigated other stackoverflow questions.
Yes, I have created an issue on cheerio github, here is the link: https://github.com/cheeriojs/cheerio/issues/1252
Yes, I am a professional web developer and this is not the first time I do node.js
Update:
After some people pointed out, the issue was that needed dom nodes were created after my page was parsed and traversed by cheerio.
So the part of the page I requested simply was not there.
Any Ideas how to bypass that?
I use versions:
{
"name": "discont",
"version": "1.0.0",
"description": "Find when the item is on sale",
"main": "index.js",
"license": "MIT",
"devDependencies": {
"express": "^4.16.4"
},
"dependencies": {
"cheerio": "^1.0.0-rc.2",
"ejs": "^2.6.1",
"request": "^2.88.0"
}
}
This is the HTML I am trying to scrape:
The link is here:
https://www.asos.com/new-look-wide-fit/new-look-wide-fit-court-shoe/prd/10675413?clr=oatmeal&SearchQuery=&cid=6461&gridcolumn=1&gridrow=9&gridsize=4&pge=1&pgesize=72&totalstyles=826
This is my code:
request(url, options, function(error, response, html) {
if (!error) {
var $ = cheerio.load(html, { withDomLvl1: false });
// console.log("product-price", $("div.product-price")[0].attribs);
console.log("product-price", $("div#product-price > div"));
}
});
The console.log returns an empty array(unable to find nested div).
This is what I get in return:
initialize {
options:
{ withDomLvl1: false,
normalizeWhitespace: false,
xml: false,
decodeEntities: true },
_root:
initialize {
'0':
{ type: 'root',
name: 'root',
namespace: 'http://www.w3.org/1999/xhtml',
attribs: {},
'x-attribsNamespace': {},
'x-attribsPrefix': {},
children: [Array],
parent: null,
prev: null,
next: null },
options:
{ withDomLvl1: false,
normalizeWhitespace: false,
xml: false,
decodeEntities: true },
length: 1,
_root: [Circular] },
length: 0,
prevObject:
initialize {
'0':
{ type: 'root',
name: 'root',
namespace: 'http://www.w3.org/1999/xhtml',
attribs: {},
'x-attribsNamespace': {},
'x-attribsPrefix': {},
children: [Array],
parent: null,
prev: null,
next: null },
options:
{ withDomLvl1: false,
normalizeWhitespace: false,
xml: false,
decodeEntities: true },
length: 1,
_root: [Circular] } }
but if I change my code to
request(url, options, function(error, response, html) {
if (!error) {
var $ = cheerio.load(html, { withDomLvl1: false });
// console.log("product-price", $("div.product-price")[0].attribs);
console.log("product-price", $("div#product-price"));
}
});
I get an array with a single element:
initialize {
'0':
{ type: 'tag',
name: 'div',
namespace: 'http://www.w3.org/1999/xhtml',
attribs:
{ class: 'product-price',
id: 'product-price',
'data-bind': 'component: { name: "product-price", params: {state: state, showGermanVatMessage: false }}' },
'x-attribsNamespace': { class: undefined, id: undefined, 'data-bind': undefined },
'x-attribsPrefix': { class: undefined, id: undefined, 'data-bind': undefined },
children: [],
parent:
{ type: 'tag',
name: 'div',
namespace: 'http://www.w3.org/1999/xhtml',
attribs: [Object],
'x-attribsNamespace': [Object],
'x-attribsPrefix': [Object],
children: [Array],
parent: [Object],
prev: [Object],
next: [Object] },
prev:
{ type: 'text',
data: '\n ',
parent: [Object],
prev: [Object],
next: [Circular] },
next:
{ type: 'text',
data: '\n ',
parent: [Object],
prev: [Circular],
next: [Object] } },
options:
{ withDomLvl1: false,
normalizeWhitespace: false,
xml: false,
decodeEntities: true },
_root:
initialize {
'0':
{ type: 'root',
name: 'root',
namespace: 'http://www.w3.org/1999/xhtml',
attribs: {},
'x-attribsNamespace': {},
'x-attribsPrefix': {},
children: [Array],
parent: null,
prev: null,
next: null },
options:
{ withDomLvl1: false,
normalizeWhitespace: false,
xml: false,
decodeEntities: true },
length: 1,
_root: [Circular] },
length: 1,
prevObject:
initialize {
'0':
{ type: 'root',
name: 'root',
namespace: 'http://www.w3.org/1999/xhtml',
attribs: {},
'x-attribsNamespace': {},
'x-attribsPrefix': {},
children: [Array],
parent: null,
prev: null,
next: null },
options:
{ withDomLvl1: false,
normalizeWhitespace: false,
xml: false,
decodeEntities: true },
length: 1,
_root: [Circular] } }
yet, I am not able to see children of the element (the children array is empty), and I am not able to perform any methods on the object such as find() or text()
Any help is welcome!
Cheerio only has access to the DOM before any special things like XHRs have happened. You would need puppeteer or nightmarejs for the post-js-rendered DOM
I am testing a basic aggregation function using counts from Sequelize and here's my type Counts:
type Creserve {
id: ID!
rDateStart: Date!
rDateEnd: Date!
grade: Int!
section: String!
currentStatus: String!
user: User!
cartlab: Cartlab!
}
type Counts {
section: String!
count: Int
}
type Query {
getBooking(id: ID!): Creserve!
allBookings: [Creserve]
getBookingByUser(userId: ID): Creserve
upcomingBookings: [Creserve]
countBookings: [Counts]
}
I am using countBookings as my query for aggregate functions and here's my resolver for the query:
countBookings: async (parent, args, {models}) =>
{
const res = await models.Creserve.findAndCountAll({
group: 'section',
attributes: ['section', [Sequelize.fn('COUNT', 'section'), 'count']]
});
return res.rows;
},
The query that it outputs is this:
Executing (default): SELECT "section", COUNT('section') AS "count" FROM "Creserve" AS "Creserve" GROUP BY "section";
And tried this query in my psql shell and it's working fine:
section | count
---------+-------
A | 2
R | 2
However, when I tried querying countBookings in my GraphQL Playground, section is returned but not the count:
{
"data": {
"countBookings": [
{
"section": "A",
"count": null
},
{
"section": "R",
"count": null
}
]
}
}
Is there something I missed out? Or is this a bug? This is the answer I tried following to with this example: https://stackoverflow.com/a/45586121/9760036
Thank you very much!
edit: returning a console.log(res.rows) outputs something like this:
[ Creserve {
dataValues: { section: 'A', count: '2' },
_previousDataValues: { section: 'A', count: '2' },
_changed: {},
_modelOptions:
{ timestamps: true,
validate: {},
freezeTableName: true,
underscored: false,
underscoredAll: false,
paranoid: false,
rejectOnEmpty: false,
whereCollection: null,
schema: null,
schemaDelimiter: '',
defaultScope: {},
scopes: [],
indexes: [],
name: [Object],
omitNull: false,
hooks: [Object],
sequelize: [Sequelize],
uniqueKeys: {} },
_options:
{ isNewRecord: false,
_schema: null,
_schemaDelimiter: '',
raw: true,
attributes: [Array] },
__eagerlyLoadedAssociations: [],
isNewRecord: false },
Creserve {
dataValues: { section: 'R', count: '2' },
_previousDataValues: { section: 'R', count: '2' },
_changed: {},
_modelOptions:
{ timestamps: true,
validate: {},
freezeTableName: true,
underscored: false,
underscoredAll: false,
paranoid: false,
rejectOnEmpty: false,
whereCollection: null,
schema: null,
schemaDelimiter: '',
defaultScope: {},
scopes: [],
indexes: [],
name: [Object],
omitNull: false,
hooks: [Object],
sequelize: [Sequelize],
uniqueKeys: {} },
_options:
{ isNewRecord: false,
_schema: null,
_schemaDelimiter: '',
raw: true,
attributes: [Array] },
__eagerlyLoadedAssociations: [],
isNewRecord: false } ]
Here's for res.count:
Executing (default): SELECT "section", COUNT('section') AS "count" FROM "Creserve" AS "Creserve" GROUP BY "section";
[ { count: '2' }, { count: '2' } ]
Problem
Actually you are doing everything right here... but what is happening here is the sequlize doesn't return plain object... It always returns the data in form of instance like that
[ Creserve {
dataValues: { section: 'A', count: '2' },
_previousDataValues: { section: 'A', count: '2' },
_changed: {},
_modelOptions:
{ timestamps: true,
Solution
I am not sure but there is no other way instead of looping and makes
response to json object...
const array = []
res.rows.map((data) => {
array.push(data.toJSON())
})
return array