stripe subscription using node js - node.js

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

Related

Authorize a Credit Card returns empty refTransId on Sandbox environment

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.

Retrieve a document query with Email firebase firestore

Code:
At line number 57 I created a route to get the data according to user's email.
But I'm unable to get the specific data that this user added to the database. The response I'm getting is looking like this. I'm stuck here although I followed the instruction that is provided in the firebase firestore documentation.
QuerySnapshot {
_firestore: Firestore {
_authCredentials: FirebaseAuthCredentialsProvider {
authProvider: [Provider],
currentUser: [User],
tokenCounter: 0,
forceRefresh: false,
auth: null,
tokenListener: [Function (anonymous)]
},
_appCheckCredentials: FirebaseAppCheckTokenProvider {
appCheckProvider: [Provider],
forceRefresh: false,
appCheck: null,
tokenListener: [Function (anonymous)]
},
type: 'firestore',
_persistenceKey: '[DEFAULT]',
_settings: FirestoreSettingsImpl {
host: 'firestore.googleapis.com',
ssl: true,
credentials: undefined,
ignoreUndefinedProperties: false,
cacheSizeBytes: 41943040,
experimentalForceLongPolling: false,
experimentalAutoDetectLongPolling: false,
useFetchStreams: true
},
_settingsFrozen: true,
_app: FirebaseAppImpl {
_isDeleted: false,
_options: [Object],
_config: [Object],
_name: '[DEFAULT]',
_automaticDataCollectionEnabled: false,
_container: [ComponentContainer]
},
_databaseId: DatabaseId { projectId: 'parlour-1bcf7', database: '(default)' },
_queue: AsyncQueueImpl {
tail: [Promise],
retryableOps: [],
_isShuttingDown: false,
delayedOperations: [Array],
failure: null,
operationInProgress: true,
skipNonRestrictedTasks: false,
timerIdsToSkip: [],
backoff: [ExponentialBackoff],
visibilityHandler: [Function (anonymous)]
},
_firestoreClient: FirestoreClient {
authCredentials: [FirebaseAuthCredentialsProvider],
appCheckCredentials: [FirebaseAppCheckTokenProvider],
asyncQueue: [AsyncQueueImpl],
databaseInfo: [DatabaseInfo],
user: [User],
clientId: 'Hoh8WrPk3BFhkBsirvQx',
authCredentialListener: [Function (anonymous)],
appCheckCredentialListener: [Function (anonymous)],
offlineComponents: [MemoryOfflineComponentProvider],
onlineComponents: [OnlineComponentProvider]
}
},
_userDataWriter: ExpUserDataWriter {
firestore: Firestore {
_authCredentials: [FirebaseAuthCredentialsProvider],
_appCheckCredentials: [FirebaseAppCheckTokenProvider],
type: 'firestore',
_persistenceKey: '[DEFAULT]',
_settings: [FirestoreSettingsImpl],
_settingsFrozen: true,
_app: [FirebaseAppImpl],
_databaseId: [DatabaseId],
_queue: [AsyncQueueImpl],
_firestoreClient: [FirestoreClient]
}
},
_snapshot: ViewSnapshot {
query: QueryImpl {
path: [ResourcePath],
collectionGroup: null,
explicitOrderBy: [],
filters: [Array],
limit: null,
limitType: 'F',
startAt: null,
endAt: null,
memoizedOrderBy: [Array],
memoizedTarget: [TargetImpl]
},
docs: DocumentSet {
comparator: [Function (anonymous)],
keyedMap: [SortedMap],
sortedSet: [SortedMap]
},
oldDocs: DocumentSet {
comparator: [Function (anonymous)],
keyedMap: [SortedMap],
sortedSet: [SortedMap]
},
docChanges: [],
mutatedKeys: SortedSet { comparator: [Function: comparator], data: [SortedMap] },
fromCache: false,
syncStateChanged: true,
excludesMetadataChanges: false
},
metadata: SnapshotMetadata { hasPendingWrites: false, fromCache: false },
query: Query {
converter: null,
_query: QueryImpl {
path: [ResourcePath],
collectionGroup: null,
explicitOrderBy: [],
filters: [Array],
limit: null,
limitType: 'F',
startAt: null,
endAt: null,
memoizedOrderBy: [Array],
memoizedTarget: [TargetImpl]
},
type: 'query',
firestore: Firestore {
_authCredentials: [FirebaseAuthCredentialsProvider],
_appCheckCredentials: [FirebaseAppCheckTokenProvider],
type: 'firestore',
_persistenceKey: '[DEFAULT]',
_settings: [FirestoreSettingsImpl],
_settingsFrozen: true,
_app: [FirebaseAppImpl],
_databaseId: [DatabaseId],
_queue: [AsyncQueueImpl],
_firestoreClient: [FirestoreClient]
}
}
}
Replace lines 64 to 67 with the following snippet
for (const doc of querySnapshot.docs) {
console.log(doc.id, '=>', doc.data())
}

Channel cache is incoherent

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.

How to read password protected PDF file in Nodejs and get it in buffer?

I tried using pdfjs-dist.
getting large json response.
var PDFJS=require('pdfjs-dist');
PDFJS.getDocument({ url: 'p1.pdf', password: '' }).then(function(pdf_doc)
{
console.log(pdf_doc);
}).catch(function(error) {
// incorrect password
// error is an object having 3 properties : name, message & code
});
Response
This is the whole response I am getting.
but I need response in buffer.
Can it be converted to buffer.
PDFDocumentProxy {
loadingTask:
{ _capability:
{ resolve: [Function], reject: [Function], promise: [Promise] },
_transport:
WorkerTransport {
messageHandler: [Object],
loadingTask: [Circular],
commonObjs: [Object],
fontLoader: [GenericFontLoader],
_params: [Object],
CMapReaderFactory: [DOMCMapReaderFactory],
destroyed: false,
destroyCapability: null,
_passwordCapability: null,
_networkStream: [PDFNodeStream],
_fullReader: [PDFNodeStreamFsFullReader],
_lastProgress: [Object],
pageCache: [],
pagePromises: [],
downloadInfoCapability: [Object],
numPages: 4,
pdfDocument: [Circular] },
_worker:
{ name: null,
destroyed: false,
postMessageTransfers: true,
verbosity: 1,
_readyCapability: [Object],
_port: [LoopbackPort],
_webWorker: null,
_messageHandler: [Object] },
docId: 'd0',
destroyed: false,
onPassword: null,
onProgress: null,
onUnsupportedFeature: null },
_pdfInfo:
{ numPages: 4,
fingerprint: '3432353738363537336c6e665361446f6f744f4a70' },
_transport:
WorkerTransport {
messageHandler:
{ sourceName: 'd0',
targetName: 'd0_worker',
comObj: [LoopbackPort],
callbackId: 1,
streamId: 1,
postMessageTransfers: true,
streamSinks: [Object],
streamControllers: [Object: null prototype] {},
callbacksCapabilities: [Object: null prototype] {},
actionHandler: [Object],
_onComObjOnMessage: [Function] },
loadingTask:
{ _capability: [Object],
_transport: [Circular],
_worker: [Object],
docId: 'd0',
destroyed: false,
onPassword: null,
onProgress: null,
onUnsupportedFeature: null },
commonObjs: { objs: [Object: null prototype] {} },
fontLoader:
GenericFontLoader {
docId: 'd0',
nativeFontFaces: [],
styleElement: null,
loadingContext: [Object],
loadTestFontId: 0 },
_params:
[Object: null prototype] {
url: 'p1.pdf',
password: '',
rangeChunkSize: 65536,
CMapReaderFactory: [Function: DOMCMapReaderFactory],
ignoreErrors: true,
pdfBug: false,
nativeImageDecoderSupport: 'none',
maxImageSize: -1,
isEvalSupported: true,
disableFontFace: true,
disableRange: false,
disableStream: false,
disableAutoFetch: false,
disableCreateObjectURL: false },
CMapReaderFactory: DOMCMapReaderFactory { baseUrl: null, isCompressed: false },
destroyed: false,
destroyCapability: null,
_passwordCapability: null,
_networkStream:
PDFNodeStream {
source: [Object],
url: [Url],
isHttp: false,
isFsUrl: true,
httpHeaders: {},
_fullRequest: [PDFNodeStreamFsFullReader],
_rangeRequestReaders: [Array] },
_fullReader:
PDFNodeStreamFsFullReader {
_url: [Url],
_done: false,
_storedError: null,
onProgress: [Function],
_contentLength: 112979,
_loaded: 112979,
_filename: null,
_disableRange: false,
_rangeChunkSize: 65536,
_isStreamingSupported: true,
_isRangeSupported: true,
_readableStream: [ReadStream],
_readCapability: [Object],
_headersCapability: [Object] },
_lastProgress: { loaded: 112979, total: 112979 },
pageCache: [],
pagePromises: [],
downloadInfoCapability:
{ resolve: [Function], reject: [Function], promise: [Promise] },
numPages: 4,
pdfDocument: [Circular] } }
*ignore below text*
efwrg rgsretg resgerstgh;ergh ;resjgysregh regjes powrjgu oiuueryoeq uieqroeqreqrilih ehr oiyeroeq ioiyeqroeq oieyqrioeq oieqyr oiyeqr oiyeqrp ioqyet oiehr oiyerh oieyreq oiyheqri iohereqk ioheqr qerioyqereq ioehqriheq rioqehriqeb ioeqrhpeq ioeqrhiqe ioqehriq ioqerhioq oirhqeipor oiqehrieq ioehqrq ioeqhrieq iohqerpq ieqhrpeq ioeqhrpeq iheqrpqe oiehrpqe ieqhrqierh ioeqhr ieqhr ioeqrh piqerh ieqhr iheqr piheqr ioheqr iheqr ioeqhrp ioqhre oieqhr oeqiyr qoeiryf pouqer poqure pouqr pouqre[q poquerq poqeur[q poqeur poqwuer poquer[ poqwur[wq poqr[ poqwhr powrq pow
You may open and read a password protected PDF like below. Working with your existing code:
var PDFJS = require('pdfjs-dist');
PDFJS.getDocument({ url: 'p1.pdf', password: '' }).then(function(pdf)
{
let text = [];
for(let i = 1; i <= pdf.numPages; i++) {
pdf.getPage(i).then(function(page) {
page.getTextContent().then(function(data) {
for(let j = 0; j < data.items.length; j++) {
text.push(data.items[j].str);
}
});
});
}
}).catch(function(error) {
// incorrect password
// error is an object having 3 properties : name, message & code
});

Aggregate function returns null GraphQL

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

Resources