Creating Custom Account for Stripe - node.js

I tried creating Stripe Custom account on test mode
Request
const createAccountTeacher = catchAsync(async (req, res) =>
{
const date = new Date();
let time = Math.floor(date.getTime() / 1000);
const email = req.body.email;
const country = req.body.country;
const createAccount = await stripe.accounts.create({
type: 'custom',
country: country,
business_type: 'individual',
tos_acceptance: {
date: time,
ip: '8.8.8.8',
},
business_profile: {
mcc: '5734',
url: 'http://google.com',
product_description: 'Good Product',
support_phone: '12345567',
product_description: 'Teaching Courses available',
support_phone: '+10000000000',
},
individual: {
first_name: 'ABC',
last_name: 'XYZ',
dob: {
day: 24,
month: 6,
year: 1992,
},
address: {
line1: '1996 W Highland Ave',
postal_code: 90002,
city: ' San Bernardino',
state: 'California',
},
email: email,
phone: '+1202-555-0454',
ssn_last_4: 9999,
id_number: 123459999,
},
external_account: {
object: 'bank_account',
country: 'US',
currency: 'usd',
account_number: '000123456789',
routing_number: 121000358,
},
capabilities: {
card_payments: { requested: true },
transfers: { requested: true },
},
});
if (createAccount) {
res.status(200).json({ data: createAccount });
}
});
Here as response
{
"data":
{
"details_submitted": true,
"type": "custom",
"metadata": {},
"id": "acct_1LNcOTD4Ev4rC234",
"object": "account",
"default_currency": "usd",
"capabilities": {
"transfers": "pending",
"card_payments": "pending"
},
"business_type": "individual",
"individual": {
"metadata": {},
"id": "person_1LNcOVD4Ev4rC234OQjvuHiP",
"object": "person",
"account": "acct_1LNcOTD4Ev4rC234",
"dob": {
"year": 1992,
"day": 24,
"month": 6
},
"requirements": {
"currently_due": [],
"past_due": [],
"eventually_due": [],
"pending_verification": [
"id_number",
"verification.document"
],
"errors": [],
"alternatives": []
},
"ssn_last_4_provided": true,
"phone": "+12025550454",
"relationship": {
"percent_ownership": null,
"title": null,
"owner": false,
"director": false,
"representative": true,
"executive": false
},
"future_requirements": {
"currently_due": [],
"past_due": [],
"eventually_due": [],
"pending_verification": [],
"errors": [],
"alternatives": []
},
"verification": {
"status": "pending",
"details": null,
"document": {
"details_code": null,
"front": null,
"details": null,
"back": null
},
"additional_document": {
"details_code": null,
"front": null,
"details": null,
"back": null
},
"details_code": null
},
"address": {
"line2": null,
"line1": "1996 W Highland Ave",
"state": "California",
"postal_code": "90002",
"city": " San Bernardino",
"country": "US"
},
"email": "lilypota#ema-sofia.eu",
"created": 1658321573,
"first_name": "ABC",
"id_number_provided": true,
"last_name": "XYZ"
},
"charges_enabled": false,
"settings": {
"dashboard": {
"display_name": "Google",
"timezone": "Etc/UTC"
},
"payouts": {
"debit_negative_balances": false,
"statement_descriptor": null,
"schedule": {
"interval": "daily",
"delay_days": 2
}
},
"card_issuing": {
"tos_acceptance": {
"ip": null,
"date": null
}
},
"bacs_debit_payments": {},
"payments": {
"statement_descriptor_kanji": null,
"statement_descriptor_kana": null,
"statement_descriptor": "GOOGLE.COM"
},
"sepa_debit_payments": {},
"card_payments": {
"statement_descriptor_prefix_kanji": null,
"statement_descriptor_prefix": null,
"statement_descriptor_prefix_kana": null,
"decline_on": {
"avs_failure": false,
"cvc_failure": false
}
},
"branding": {
"icon": null,
"secondary_color": null,
"logo": null,
"primary_color": null
}
},
"tos_acceptance": {
"ip": "8.8.8.8",
"user_agent": null,
"date": 1658321567
},
"requirements": {
"current_deadline": null,
"past_due": [],
"errors": [],
"disabled_reason": "requirements.pending_verification",
"pending_verification": [
"individual.id_number",
"individual.verification.document"
],
"currently_due": [],
"eventually_due": [],
"alternatives": []
},
"payouts_enabled": false,
"company": {
"tax_id_provided": false,
"phone": "+12025550454",
"owners_provided": true,
"verification": {
"document": {
"details_code": null,
"front": null,
"details": null,
"back": null
}
},
"address": {
"line2": null,
"line1": "1996 W Highland Ave",
"state": "California",
"postal_code": "90002",
"city": " San Bernardino",
"country": "US"
},
"executives_provided": true,
"directors_provided": true,
"name": null
},
"external_accounts": {
"has_more": false,
"total_count": 1,
"object": "list",
"url": "/v1/accounts/acct_1LNcOTD4Ev4rC234/external_accounts",
"data": [
{
"last4": "6789",
"account_holder_name": null,
"metadata": {},
"id": "ba_1LNcOUD4Ev4rC234XwzzfiqR",
"object": "bank_account",
"account_type": null,
"default_for_currency": true,
"account_holder_type": null,
"account": "acct_1LNcOTD4Ev4rC234",
"status": "new",
"available_payout_methods": [
"standard"
],
"bank_name": "BANK OF AMERICA, N.A.",
"currency": "usd",
"country": "US",
"routing_number": "121000358",
"fingerprint": "gqPBt6FUMZJkqc9q"
}
]
},
"future_requirements": {
"current_deadline": null,
"past_due": [],
"errors": [],
"disabled_reason": null,
"pending_verification": [],
"currently_due": [],
"eventually_due": [],
"alternatives": []
},
"country": "US",
"email": null,
"created": 1658321576,
"business_profile": {
"support_email": null,
"product_description": "Teaching Courses available",
"mcc": "5734",
"support_url": null,
"support_address": null,
"url": "http://google.com",
"support_phone": "+10000000000",
"name": null
}
}
}
Custom Account is created but the problem it is restricted because of identity document
I am trying to upload the document like this
const updateAccount = catchAsync(async (req, res) => {
// let imagepath = ${req.protocol}://${req.get('host')}/uploads/${req.file.filename};
if(req.file.path){
const file = await stripe.files.create({
purpose: 'identity_document',
file: {
data: fs.readFileSync(req.file.path),
name: req.file.filename,
type: 'application/octet-stream',
},
}, {
stripeAccount: 'acct_1LNcOTD4Ev4rC234',
});
if(file){
res.status(200).json({data:file})
}
}
})
Still the custom account is restricted.
I would appreciate little help.

Related

$aggregation and $look up in the same collection- mongodb not get child

I have an product option schema where I have chield material and add-on type
Product_options
const productOptionsSchema = new mongoose.Schema({
category: [{
value: { type: String },
display: { type: Number },
display_order: { type: String },
categoryImage: { type: String },
parent_id: { type: mongoose.Schema.Types.ObjectId },
parent_name: { type: String }
}],
material: [{
value: { type: String },
display: { type: Number },
display_order: { type: String },
price: { type: String }
}],
addon_type: [{
// addon_id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'AddOnDetails'
// }
}],
design: [{
// design_id: {
type: mongoose.Schema.Types.ObjectId,
ref: 'DesignDetails'
// }
}]
}, {
timestamps: true
})
const Product_options = mongoose.model('Product_options', productOptionsSchema)
i want to add one more key 'isChildExist' if have any chield of category have parent_id == parent_id . my node js code is
const cat = await Product_options.aggregate( [
{
$unwind: {
path: "$category",
preserveNullAndEmptyArrays: true
}
},
{
$lookup: {
from: 'Product_options.category',
localField: '_id',
foreignField: 'parent_id',
as: 'category.isChildExist'
}
},
{
"$project": {
"_id": 0,
"category": 1,
}
}
] );
res.json({
msg: 'Success!',
cat
})
my current response is whenre isChildExist is blank :
{
"msg": "Success!",
"cat": [
{
"category": {
"value": "Rudraksha",
"display": 1,
"display_order": "",
"categoryImage": "",
"parent_id": null,
"parent_name": null,
"_id": "63aeac69f969cf78856b7db9",
"isChildExist": []
}
},
{
"category": {
"value": "Bead Bracelet",
"display": 1,
"display_order": "",
"categoryImage": "",
"parent_id": null,
"parent_name": null,
"_id": "63aeae05f969cf78856b80b2",
"isChildExist": []
}
},
{
"category": {
"value": "Gemstones",
"display": 1,
"display_order": "1",
"categoryImage": "",
"parent_id": null,
"parent_name": null,
"_id": "63aeb968f969cf78856b8cd9",
"isChildExist": []
}
},
{
"category": {
"value": "Natural Yellow Sapphire - Pukhraj ",
"display": 1,
"display_order": "1",
"categoryImage": "",
"parent_id": "63aeb968f969cf78856b8cd9",
"parent_name": "Gemstones",
"_id": "63aec39bf969cf78856bb9c3",
"isChildExist": []
}
},
{
"category": {
"value": "Natural Blue Sapphire - Neelam",
"display": 1,
"display_order": "1",
"categoryImage": "",
"parent_id": "63aeb968f969cf78856b8cd9",
"parent_name": "Gemstones",
"_id": "63aebe42f969cf78856b9fae",
"isChildExist": []
}
},
{
"category": {
"value": "Natural Ruby - Manik ",
"display": 1,
"display_order": "",
"categoryImage": "",
"parent_id": "63aeb968f969cf78856b8cd9",
"parent_name": "Gemstones",
"_id": "63aebe54f969cf78856b9fd9",
"isChildExist": []
}
},
{
"category": {
"value": "Natural Hessonite - Gomed",
"display": 1,
"display_order": "",
"categoryImage": "",
"parent_id": "63aeb968f969cf78856b8cd9",
"parent_name": "Gemstones",
"_id": "63aebe83f969cf78856ba076",
"isChildExist": []
}
},
{
"category": {
"value": "Natural Coral - Moonga ",
"display": 1,
"display_order": "",
"categoryImage": "",
"parent_id": "63aeb968f969cf78856b8cd9",
"parent_name": "Gemstones",
"_id": "63aebe9ff969cf78856ba0a8",
"isChildExist": []
}
},
{
"category": {
"value": "Natural Emerald - Panna ",
"display": 1,
"display_order": "",
"categoryImage": "",
"parent_id": "63aeb968f969cf78856b8cd9",
"parent_name": "Gemstones",
"_id": "63aebeb5f969cf78856ba0de",
"isChildExist": []
}
}
]
}
i expect isChildExist have data in gemstone but current is blank array
{
"category": {
"value": "Gemstones",
"display": 1,
"display_order": "1",
"categoryImage": "",
"parent_id": null,
"parent_name": null,
"_id": "63aeb968f969cf78856b8cd9",
"isChildExist": [
{
"value": "Natural Yellow Sapphire - Pukhraj ",
"display": 1,
"display_order": "1",
"categoryImage": "",
"parent_id": "63aeb968f969cf78856b8cd9",
"parent_name": "Gemstones",
"_id": "63aec39bf969cf78856bb9c3",
"child": []
},{
"value": "Natural Blue Sapphire - Neelam",
"display": 1,
"display_order": "1",
"categoryImage": "",
"parent_id": "63aeb968f969cf78856b8cd9",
"parent_name": "Gemstones",
"_id": "63aebe42f969cf78856b9fae",
"child": []
}
]
}
},
Problem is in $lookup
Try this code:
const cat = await Product_options.aggregate([{
$unwind: {
path: "$category",
preserveNullAndEmptyArrays: true
}
},
{
$lookup: {
from: 'Product_options',
let: {
category_id: "$category._id"
},
pipeline: [{
$match: {
$expr: {
$and: [{
$eq: ["$category.parent_id", "$$category_id"]
}, ]
}
}
},
{
$project: {
_id: 0,
category: 1,
}
}
],
as: "category.isChildExist"
}
},
{
$project: {
_id: 0,
category: 1
}
}
]);

How to get Product and Quantity information from payment_intent.succeeded event via Webhooks in Stripe?

Here is how I'm initializing the Checkout Process in Node.js.
let email = req.body.email
let product_id = req.body.product_id
let YOUR_DOMAIN = 'http://localhost:8000'
const session = await stripe.checkout.sessions.create({
line_items: [{
price: product_id,
adjustable_quantity: {
enabled: true,
minimum: 1,
maximum: 5,
},
quantity: 1,
}],
customer_email: email,
mode: 'payment',
success_url: `${YOUR_DOMAIN}/payment-success`,
cancel_url: `${YOUR_DOMAIN}/payment-failure`,
});
Here are the events I have subscribed to in Webhooks
payment_intent.succeeded
checkout.session.completed
Object Received in Payment Intent Succeeded
{
"id": "evt_1KEqIxI5cib7rtVMoKMkak96",
"object": "event",
"api_version": "2020-03-02",
"created": 1641453754,
"data": {
"object": {
"id": "pi_1KEqIeI5cib7rtVMcz8zsXys",
"object": "payment_intent",
"amount": 59700,
"amount_capturable": 0,
"amount_received": 59700,
"application": null,
"application_fee_amount": null,
"automatic_payment_methods": null,
"canceled_at": null,
"cancellation_reason": null,
"capture_method": "automatic",
"charges": {
"object": "list",
"data": [{
"id": "ch_1KEqIvI5cib7rtVMYUVn5gfQ",
"object": "charge",
"amount": 59700,
"amount_captured": 59700,
"amount_refunded": 0,
"application": null,
"application_fee": null,
"application_fee_amount": null,
"balance_transaction": "txn_1KEqIwI5cib7rtVMGfJlEahg",
"billing_details": {
"address": {
"city": "NY",
"country": "US",
"line1": "sada",
"line2": "asd",
"postal_code": "10001",
"state": "NY"
},
"email": "test#gmail.com",
"name": "John Doe",
"phone": null
},
"calculated_statement_descriptor": "VIDEOFORM",
"captured": true,
"created": 1641453753,
"currency": "usd",
"customer": "cus_KufeYc1hifvZGA",
"description": null,
"destination": null,
"dispute": null,
"disputed": false,
"failure_code": null,
"failure_message": null,
"fraud_details": {},
"invoice": null,
"livemode": false,
"metadata": {},
"on_behalf_of": null,
"order": null,
"outcome": {
"network_status": "approved_by_network",
"reason": null,
"risk_level": "normal",
"risk_score": 25,
"seller_message": "Payment complete.",
"type": "authorized"
},
"paid": true,
"payment_intent": "pi_1KEqIeI5cib7rtVMcz8zsXys",
"payment_method": "pm_1KEqIuI5cib7rtVMYPWlLV8S",
"payment_method_details": {
"card": {
"brand": "visa",
"checks": {
"address_line1_check": "pass",
"address_postal_code_check": "pass",
"cvc_check": "pass"
},
"country": "US",
"exp_month": 1,
"exp_year": 2023,
"fingerprint": "QaiTi5PATFO8ZoC3",
"funding": "credit",
"installments": null,
"last4": "4242",
"mandate": null,
"network": "visa",
"three_d_secure": null,
"wallet": null
},
"type": "card"
},
"receipt_email": null,
"receipt_number": null,
"receipt_url": "https://pay.stripe.com/receipts/acct_1GhUSuI5cib7rtVM/ch_1KEqIvI5cib7rtVMYUVn5gfQ/rcpt_KufeysPW3LD8Yu47q14iYOIIlcGth9h",
"refunded": false,
"refunds": {
"object": "list",
"data": [],
"has_more": false,
"total_count": 0,
"url": "/v1/charges/ch_1KEqIvI5cib7rtVMYUVn5gfQ/refunds"
},
"review": null,
"shipping": null,
"source": null,
"source_transfer": null,
"statement_descriptor": null,
"statement_descriptor_suffix": null,
"status": "succeeded",
"transfer_data": null,
"transfer_group": null
}],
"has_more": false,
"total_count": 1,
"url": "/v1/charges?payment_intent=pi_1KEqIeI5cib7rtVMcz8zsXys"
},
"client_secret": "pi_1KEqIeI5cib7rtVMcz8zsXys_secret_uZwm3uziwfaWePgTHENYXeraD",
"confirmation_method": "automatic",
"created": 1641453736,
"currency": "usd",
"customer": "cus_KufeYc1hifvZGA",
"description": null,
"invoice": null,
"last_payment_error": null,
"livemode": false,
"metadata": {},
"next_action": null,
"on_behalf_of": null,
"payment_method": "pm_1KEqIuI5cib7rtVMYPWlLV8S",
"payment_method_options": {
"card": {
"installments": null,
"mandate_options": null,
"network": null,
"request_three_d_secure": "automatic"
}
},
"payment_method_types": ["card"],
"processing": null,
"receipt_email": null,
"review": null,
"setup_future_usage": null,
"shipping": null,
"source": null,
"statement_descriptor": null,
"statement_descriptor_suffix": null,
"status": "succeeded",
"transfer_data": null,
"transfer_group": null
}
},
"livemode": false,
"pending_webhooks": 3,
"request": {
"id": "req_Y87umQuitz9WCc",
"idempotency_key": "a4b6af76-73d8-49b4-8393-9017e673af7e"
},
"type": "payment_intent.succeeded"
}
Object Received in Checkout Session Completed
{
"id": "evt_1KEqQOI5cib7rtVMRwAHWDvV",
"object": "event",
"api_version": "2020-03-02",
"created": 1641454214,
"data": {
"object": {
"id": "cs_test_a1AQ9EKIaxi8dXFAJzZ86xYm5meRkWb9Vu0eLowfkiKgUO4cyToooBzSTd",
"object": "checkout.session",
"after_expiration": null,
"allow_promotion_codes": null,
"amount_subtotal": 59700,
"amount_total": 59700,
"automatic_tax": {
"enabled": false,
"status": null
},
"billing_address_collection": null,
"cancel_url": "http://localhost:8000/payment-failure",
"client_reference_id": null,
"consent": null,
"consent_collection": null,
"currency": "usd",
"customer": "cus_Kuflo6N0n4HTzL",
"customer_details": {
"email": "test#gmail.com",
"phone": null,
"tax_exempt": "none",
"tax_ids": []
},
"customer_email": "test#gmail.com",
"expires_at": 1641540596,
"livemode": false,
"locale": null,
"mode": "payment",
"payment_intent": "pi_1KEqQ4I5cib7rtVMyND6NhQG",
"payment_method_options": {},
"payment_method_types": ["card"],
"payment_status": "paid",
"phone_number_collection": {
"enabled": false
},
"recovered_from": null,
"setup_intent": null,
"shipping": null,
"shipping_address_collection": null,
"shipping_options": [],
"shipping_rate": null,
"status": "complete",
"submit_type": null,
"subscription": null,
"success_url": "http://localhost:8000/payment-success",
"total_details": {
"amount_discount": 0,
"amount_shipping": 0,
"amount_tax": 0
},
"url": null
}
},
"livemode": false,
"pending_webhooks": 4,
"request": {
"id": null,
"idempotency_key": null
},
"type": "checkout.session.completed"
}
I'm unable to figure out how to get the Product ID and the Quantity. Could anyone suggest the right approach here?
You can find the Product and the quantity from the Checkout Session by using expand on the line_items property. The code should look like this.
// In "checkout.session.completed" event handler, get the ID of the Checkout Session
const id = event.data.object.id; // "cs_xxx"
// Retrieve the Checkout Session with expand
const session = await stripe.checkout.sessions.retrieve(id, {
expand: [ "line_items" ]
});
// Get the quantity
console.log(session.line_items.data[0].quantity);
// Get the product ID
console.log(session.line_items.data[0].price.product);

in apollo client pagination configuration with "merge" function, existing cached data always is empty even after calling fetchMore

I'm new to Apollo Client and I'm trying to implement pagination for my product list. but I can't figure out why the existing parameter in the merge function always returns empty. my incoming parameter always updates with a new list each time I call fetchMore but the existing parameter always is empty That's why I can't merge the new list with the old one.
this is my client configuration:
/* eslint-disable #typescript-eslint/no-unsafe-return */
import { ApolloClient, InMemoryCache } from '#apollo/client'
import { AppEndpoints } from './const'
import { createLink } from './links'
const cache = new InMemoryCache({
typePolicies: {
ListProductSearchType: {
fields: {
items: {
keyArgs: false,
// eslint-disable-next-line prefer-arrow/prefer-arrow-functions
merge: (existing = [], incoming, { args }) => {
console.log('>>>args', args)
console.log('>>>existing', existing) // it's always empty
console.log('>>>incoming', incoming)
return [...existing, ...incoming]
},
},
},
},
},
})
const link = createLink(AppEndpoints.main)
const client = new ApolloClient({
cache,
// ssrMode: false,
link,
defaultOptions: {
mutate: {
errorPolicy: 'ignore',
},
query: {
fetchPolicy: 'cache-first',
},
},
})
export default client
this is my Graphql response:
{
"data": {
"productSearch": {
"listDto": {
"count": 10,
"items": [
{
"id": "1d37d4fe-79d9-440a-8869-2dca0327791b",
"code": "780133 Iceland Poppy",
"isMyfavorite": false,
"currency": "$",
"imageUrl": "https://devcdn.sonbol.nl/Product/flower.jpg",
"price": 429.29,
"compareAtPrice": 240.4,
"hasDiscount": true,
"visited": 27685,
"salesCount": 8148,
"createdDateTime": "2020-12-14T06:02:38.0469339+00:00",
"__typename": "ProductSearchDto"
},
{
"id": "ae15c925-75ef-4dde-aa07-0eeb1bbb75c8",
"code": "330338 Amaranth",
"isMyfavorite": false,
"currency": "$",
"imageUrl": "https://devcdn.sonbol.nl/Product/flower.jpg",
"price": 234.8,
"compareAtPrice": 211.32,
"hasDiscount": true,
"visited": 27660,
"salesCount": 6374,
"createdDateTime": "2020-12-05T15:04:37.4237772+00:00",
"__typename": "ProductSearchDto"
},
{
"id": "de23a1f8-5e79-4cf9-88f0-57518c42a82c",
"code": "690156 Snowflake",
"isMyfavorite": false,
"currency": "$",
"imageUrl": "https://devcdn.sonbol.nl/Product/flower.jpg",
"price": 110.11,
"compareAtPrice": 88.09,
"hasDiscount": true,
"visited": 27141,
"salesCount": 2278,
"createdDateTime": "2020-10-18T11:27:38.0467775+00:00",
"__typename": "ProductSearchDto"
},
{
"id": "fb298a9c-a3d7-4c0e-a96e-a552b98d340f",
"code": "375033 Peony",
"isMyfavorite": false,
"currency": "$",
"imageUrl": "https://devcdn.sonbol.nl/Product/flower.jpg",
"price": 337.68,
"compareAtPrice": 151.96,
"hasDiscount": true,
"visited": 27050,
"salesCount": 2483,
"createdDateTime": "2020-12-06T22:57:37.4236274+00:00",
"__typename": "ProductSearchDto"
},
{
"id": "d017638f-3062-49bf-99cc-0e06ba0882b9",
"code": "112093 Hyacinth, wild",
"isMyfavorite": false,
"currency": "$",
"imageUrl": "https://devcdn.sonbol.nl/Product/flower.jpg",
"price": 460.43,
"compareAtPrice": 326.91,
"hasDiscount": true,
"visited": 26843,
"salesCount": 530,
"createdDateTime": "2020-11-10T23:13:37.4235865+00:00",
"__typename": "ProductSearchDto"
},
{
"id": "682a3c04-a462-4cbd-be8f-8b65d024b73f",
"code": "914276 Iceland Poppy",
"isMyfavorite": false,
"currency": "$",
"imageUrl": "https://devcdn.sonbol.nl/Product/flower.jpg",
"price": 126.81,
"compareAtPrice": 100.18,
"hasDiscount": true,
"visited": 24055,
"salesCount": 6328,
"createdDateTime": "2021-01-05T11:05:38.0469862+00:00",
"__typename": "ProductSearchDto"
},
{
"id": "c48819e2-52f4-4324-9f11-616efbc1a744",
"code": "494847 Persian Candytuft",
"isMyfavorite": false,
"currency": "$",
"imageUrl": "https://devcdn.sonbol.nl/Product/flower.jpg",
"price": 405.95,
"compareAtPrice": 288.22,
"hasDiscount": true,
"visited": 23713,
"salesCount": 7474,
"createdDateTime": "2020-10-23T16:24:37.4236199+00:00",
"__typename": "ProductSearchDto"
},
{
"id": "7118ddd5-56cf-4e12-9665-accb5abf3f73",
"code": "682251 Violet",
"isMyfavorite": false,
"currency": "$",
"imageUrl": "https://devcdn.sonbol.nl/Product/flower.jpg",
"price": 184.09,
"compareAtPrice": 90.2,
"hasDiscount": true,
"visited": 23448,
"salesCount": 6196,
"createdDateTime": "2020-10-12T08:36:38.0469107+00:00",
"__typename": "ProductSearchDto"
},
{
"id": "9e69b51a-560e-4d5e-b956-d9438d996c61",
"code": "982376 Calendula",
"isMyfavorite": false,
"currency": "$",
"imageUrl": "https://devcdn.sonbol.nl/Product/flower.jpg",
"price": 62.25,
"compareAtPrice": 38.6,
"hasDiscount": true,
"visited": 23300,
"salesCount": 9072,
"createdDateTime": "2020-10-10T14:24:38.0463778+00:00",
"__typename": "ProductSearchDto"
},
{
"id": "623dde57-8daf-4637-b2d3-0ebbf166aad0",
"code": "138453 Manchineel",
"isMyfavorite": false,
"currency": "$",
"imageUrl": "https://devcdn.sonbol.nl/Product/flower.jpg",
"price": 121.92,
"compareAtPrice": 56.08,
"hasDiscount": true,
"visited": 22373,
"salesCount": 4735,
"createdDateTime": "2020-10-11T12:04:37.4235489+00:00",
"__typename": "ProductSearchDto"
}
],
"__typename": "ListProductSearchType"
},
"__typename": "GenericQueryResponseProductSearchType"
}
}
}
and this is my query:
export const GetProductSearchDocument = /*#__PURE__*/ gql`
query GetProductSearch($filter: GenericFilterRequestProductSearchReqInputType!) {
productSearch(filter: $filter) {
listDto {
count
items {
id
code
isMyfavorite
currency
imageUrl
price
compareAtPrice
hasDiscount
visited
salesCount
createdDateTime
}
}
}
}
i'm calling fetchMore like this:
const [pageIndex, setpageIndex] = useState(0)
const { productResults, loading, fetchMore } = useQueryProductSearchData()
// eslint-disable-next-line #typescript-eslint/unbound-method
const { formatMessage } = useIntl()
useEffect(() => {
if (pageIndex !== 0) {
fetchMore({
variables: {
filter: {
pageSize: 10,
pageIndex,
dto: {
filters: [],
},
},
},
})
}
}, [fetchMore, pageIndex])
const onViewMore = () => {
setpageIndex((pre: any) => pre + 1)
}
Try adding keyFields: [], like:
typePolicies: {
ListProductSearchType: {
keyFields: [],
fields: {
items: {
keyArgs: false,
// eslint-disable-next-line prefer-arrow/prefer-arrow-functions
merge: (existing = [], incoming, { args }) => {
console.log('>>>args', args)
console.log('>>>existing', existing) // it's always empty
console.log('>>>incoming', incoming)
return [...existing, ...incoming]
},
},
},
},
},
You should add read function to your field policy
const cache = new InMemoryCache({
typePolicies: {
ListProductSearchType: {
fields: {
items: {
//your code here
//then add this function
read(existing) {
return existing
},
},
},
},
},
})

Cannot get correct result using JSON.stringify() and JSON.parse()

Trying to retrieve the data from API and use them as objects.
The problem is I did not get the correct result after JSON.parse() and I do not know how to access the data (not knowing the index or parameters to retrieve specific data).
Function in Express using axios:
var result_post = axios.post(url_post, post_data, post_config);
result_post.then(function (res){
//console.log("RESPONSE: ", res);
json_result_post = res['data'];
json_result_post = JSON.stringify(json_result_post, null, 2);
json_result_post_parse = JSON.parse(json_result_post);
console.log(json_result_post_parse);
//cconsole.log(json_result_post);
fs.writeFile("data_post.json", json_result_post, function(err){
if(err){
console.log(err);
}
});
//json_result_post_parse = JSON.parse(json_result_post);
//console.log("RESPONSE: ", res);
})
.catch(function (err){
console.log("AXIOS ERROR: ", err);
});
Some Data after JSON.stringify():
{
"body-json": {
"emp_no": 80000,
"email": "80000#cloud-spartan.com",
"first_name": "Odoardo",
"last_name": "Ranft",
"birth_date": "1963-06-23",
"gender": "F",
"hire_date": "1994-07-03",
"salaries": [
{
"salary": 40000,
"from_date": "1994-07-03",
"to_date": "1995-07-03"
},
{
"salary": 41003,
"from_date": "1995-07-03",
"to_date": "1996-07-02"
},
{
"salary": 41720,
"from_date": "1996-07-02",
"to_date": "1997-07-02"
},
{
"salary": 44005,
"from_date": "1997-07-02",
"to_date": "1998-07-02"
},
{
"salary": 45659,
"from_date": "1998-07-02",
"to_date": "1999-07-02"
},
{
"salary": 46077,
"from_date": "1999-07-02",
"to_date": "2000-07-01"
},
{
"salary": 48065,
"from_date": "2000-07-01",
"to_date": "2001-07-01"
},
{
"salary": 49474,
"from_date": "2001-07-01",
"to_date": "2002-07-01"
},
{
"salary": 50059,
"from_date": "2002-07-01",
"to_date": "9999-01-01"
}
],
"departments": [
{
"dept_no": "d005",
"dept_name": "Development",
"from_date": "1994-07-03",
"to_date": "9999-01-01",
"dept_manager": [
{
"emp_no": 110511,
"first_name": "DeForest",
"last_name": "Hagimont",
"email": "110511#cloud-spartan.com",
"from_date": "1985-01-01",
"to_date": "1992-04-25"
},
{
"emp_no": 110567,
"first_name": "Leon",
"last_name": "DasSarma",
"email": "110567#cloud-spartan.com",
"from_date": "1992-04-25",
"to_date": "9999-01-01"
}
]
}
],
"title": [
{
"title": "Engineer",
"from_date": "1994-07-03",
"to_date": "2000-07-02"
},
{
"title": "Senior Engineer",
"from_date": "2000-07-02",
"to_date": "9999-01-01"
}
]
},
Console after JSON.parse():
{ 'body-json':
{ emp_no: 80000,
email: '80000#cloud-spartan.com',
first_name: 'Odoardo',
last_name: 'Ranft',
birth_date: '1963-06-23',
gender: 'F',
hire_date: '1994-07-03',
salaries:
[ [Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object],
[Object] ],
departments: [ [Object] ],
title: [ [Object], [Object] ] },
You a problem in your code, you do not need to stringfy before parse.
After parsing you can now access the emp_no like this:
json_result_post_parse["body-json"].emp_no
Below is a working sample code:
const data = `{
"body-json": {
"emp_no": 80000,
"email": "80000#cloud-spartan.com",
"first_name": "Odoardo",
"last_name": "Ranft",
"birth_date": "1963-06-23",
"gender": "F",
"hire_date": "1994-07-03",
"salaries": [
{
"salary": 40000,
"from_date": "1994-07-03",
"to_date": "1995-07-03"
},
{
"salary": 41003,
"from_date": "1995-07-03",
"to_date": "1996-07-02"
}
]
}
}`
function testjson() {
const parsedData = JSON.parse(data);
console.log(parsedData["body-json"].emp_no)
}
testjson()
To get a specific data you have to declare a variable or an object first.
For example you want emp_no, then
var emp = body-json.emp_no
or if you want salaries then
var salary = body-json.salaries.salary

Building mongoose queries programmatically

I'm trying to do a kind of a complex mongoose query. I have searched around and found solutions asking for single variables(with if) and building the query object, but I wanted to know if there is a simpler way because I would be building a query with about 40 non required parameters, for example right now in my req.body I have:
{ searchParams:
{ publicationType: 'Venta',
subtype: [ 'Duplex', 'Cabaña' ],
address:
{
streetNumber: '1312',
streetName: 'José María Bosch',
city: 'Villa Bosch',
state: 'Buenos Aires',
country: 'Argentina' }
}
}
All the names are the same in the database, what I have to do I search if publicationType matches, if the address matches and finally for sub type if any of those array items matches since subtype is a string. Is there any way to do it without an if for each field?
Right now I did this simple query to try out
router.post('/search', (req, res, next) => {
model.Dwelling.find(req.body.searchParams).lean().exec().then(
dwellings => res.send({dwellings})
).catch(next);
});
It works on publicationType and subtype buy not on address.
this is an object in my data base:
{
"_id": {
"$oid": "5af06167ea174f00142bab91"
},
"publicationType": "Alquiler",
"address": {
"latitude": -34.59250669999999,
"altitude": -58.571258599999965,
"streetNumber": "1312",
"streetName": "José María Bosch",
"city": "Villa Bosch",
"state": "Buenos Aires",
"country": "Argentina"
},
"type": "Residencial",
"subtype": "Casa",
"currency": "",
"price": 50000,
"occupationStatus": "Disponible",
"spaces": {
"rooms": 3,
"floors": 0,
"bedrooms": 0,
"closets": 0,
"bathRoom": 0,
"toilette": 0,
"living": false,
"livingDining": false,
"diningRoom": false,
"kitchen": false,
"kitchenDining": false,
"terrace": false,
"balcony": false,
"backYard": false,
"swimmingPool": false,
"barbecue": false,
"garage": "No",
"laundryRoom": "No"
},
"features": {
"status": "Desconocido",
"orientation": "Desconocida",
"luminosity": "Desconocida",
"heating": [
{
"value": "No posee",
"label": "No posee"
}
],
"refurbished": false,
"repair": "No"
},
"services": {
"gas": true,
"water": true,
"sewer": true,
"phone": true,
"pavement": true,
"electricity": true,
"cableTv": true
},
"legal": {
"bank": false,
"prof": false
},
"generalDescription": "Desc 1",
"privateDescription": "Desc 2",
"siocId": 713675,
"createdAt": {
"$date": "2018-05-07T14:23:35.230Z"
},
"updatedAt": {
"$date": "2018-05-07T14:23:35.230Z"
},
"__v": 0
}

Resources