Listing Firebase Storage objects omits all metadata - javascript

I've been trying to get a list of all files in a specific folder of my storage bucket and it works pretty well but there is no information about the meta of the object as described in this document: https://cloud.google.com/storage/docs/json_api/v1/objects#resource
The shape of the item object is not the same and instead gives a "ReferenceCompat" for each item in the array.
Instead - the only provided properties are bucket, fullPath and name.
Does anyone know why this is?
https://firebase.google.com/docs/storage/web/list-files
const storageRef = firebase.storage().ref(folder);
const listFiles = function listFilesAndSaveToSlice() {
storageRef
.listAll()
.then((res) => {
res.items.forEach((item) => {
let {name, id, owner, acl, ...etc} = item;
// {name: name, id: undefined, ...undefined}
});
})
.catch((error) => {
});
};
This is the object provided instead of what's expected:
ReferenceCompat: {
"_delegate": {
"_service": {
"app": {
"name": "[DEFAULT]",
"automaticDataCollectionEnabled": false,
"options": {
"apiKey": "xxxxxxx-xxxxxxxxx",
"authDomain": "xxxxxx",
"projectId": "xxxx",
"storageBucket": "xxxxxx",
"messagingSenderId": "xxxxxxxxx",
"appId": "xxxxxxxx"
}
},
"_authProvider": {
"name": "auth-internal",
"container": {
"name": "[DEFAULT]",
"providers": {}
},
"component": {
"name": "auth-internal",
"multipleInstances": false,
"instantiationMode": "LAZY",
"type": "PRIVATE"
},
"instances": {},
"instancesDeferred": {},
"onInitCallbacks": {}
},
"_appCheckProvider": {
"name": "app-check-internal",
"container": {
"name": "[DEFAULT]",
"providers": {}
},
"component": null,
"instances": {},
"instancesDeferred": {},
"onInitCallbacks": {}
},
"_pool": {},
"_firebaseVersion": "8.6.5",
"_bucket": {
"bucket": "xxxxx",
"path_": ""
},
"_host": "firebasestorage.googleapis.com",
"_appId": null,
"_deleted": false,
"_maxOperationRetryTime": 120000,
"_maxUploadRetryTime": 600000,
"_requests": {}
},
"_location": {
"bucket": "xxxxxxxxxx",
"path_": "samples/coming to an end v2.mp3.asd"
}
},
"storage": {
"app": {
"name": "[DEFAULT]",
"automaticDataCollectionEnabled": false,
"options": {
"apiKey": "xxxxxx",
"authDomain": "xxxxxx",
"projectId": "xxxxx",
"storageBucket": "xxxxx",
"messagingSenderId": "xxxxx",
"appId": "xxxx"
}
},
"_delegate": {
"app": {
"name": "[DEFAULT]",
"automaticDataCollectionEnabled": false,
"options": {
"apiKey": "xxxxxxxxxxxxxx",
"authDomain": "xxxxxxx",
"projectId": "xxxxxx",
"storageBucket": "xxxxx",
"messagingSenderId": "xxxxx",
"appId": "xxxxxx"
}
},
"_authProvider": {
"name": "auth-internal",
"container": {
"name": "[DEFAULT]",
"providers": {}
},
"component": {
"name": "auth-internal",
"multipleInstances": false,
"instantiationMode": "LAZY",
"type": "PRIVATE"
},
"instances": {},
"instancesDeferred": {},
"onInitCallbacks": {}
},
"_appCheckProvider": {
"name": "app-check-internal",
"container": {
"name": "[DEFAULT]",
"providers": {}
},
"component": null,
"instances": {},
"instancesDeferred": {},
"onInitCallbacks": {}
},
"_pool": {},
"_firebaseVersion": "8.6.5",
"_bucket": {
"bucket": "megatech-ltd.appspot.com",
"path_": ""
},
"_host": "firebasestorage.googleapis.com",
"_appId": null,
"_deleted": false,
"_maxOperationRetryTime": 120000,
"_maxUploadRetryTime": 600000,
"_requests": {}
},
"INTERNAL": {}
}
}

As mentioned in the firebase storage api docs, list() returns a ListResult which in turn may contain multiple Reference objects.
If you want to fetch the metadata for all of the objects returned by list(), you'll need to call Reference.getMetadata() on each individual file returned.

Related

How to Parse nested Json In Java script

I have this json in js,
and i am trying to get the key from the "Data" Object, like the SessionId and Email.
Please Help...
{
"HasError": false,
"Errors": [],
"ObjectName": "WebCheckoutCreateSessionResponse",
"Data": {
"HasError": false,
"ReturnCode": 0,
"ReturnMessage": null,
"SessionId": "abcde",
"SessionUrl": "https://pci.aaa.com/WebCheckout/Angular/Checkout.html#!/ZCreditWebCheckout/55cf7d1306b2bcc15d791dde524d2b4f616421172e6d75a013597c8dd2668843",
"RequestData": {
"Key": "ad",
"Local": "He",
"UniqueId": "<InvNo>1705</InvNo><InvYear>3102</InvYear><SugMismah>15</SugMismah><key>ad</key>",
"SuccessUrl": "",
"CancelUrl": "",
"CallbackUrl": "",
"PaymentType": "regular",
"CreateInvoice": false,
"AdditionalText": "",
"ShowCart": true,
"ThemeColor": "005ebb",
"Installments": {
"Type": "regular",
"MinQuantity": 1,
"MaxQuantity": 12
},
"Customer": {
"Email": "someone#gmail.com",
"Name": "Demo Client",
"PhoneNumber": "077-3233190",
"Attributes": {
"HolderId": "none",
"Name": "required",
"PhoneNumber": "required",
"Email": "optional"
}
},
"CartItems": [
{
"Amount": 117,
"Currency": "US",
"Name": "Danny ",
"Description": "Hi ",
"Quantity": 1,
"Image": "https://www.aaa.com/site/wp-content/themes/z-credit/img/decisions/decision2.png",
"IsTaxFree": false
}
],
"GetCurrencyCode": "376",
"BitButtonEnabled": true,
"MaxPayButtonEnabled": true,
"ApplePayButtonEnabled": true,
"GooglePayButtonEnabled": true,
"ShowTotalSumInPayButton": true
}
},
"ResponseType": 0
}
const population = JSON.parse(xhr.responseText);
for (const key in population) {
if (population.hasOwnProperty(key)) {
console.log(`${key}: ${population[key]}`);
}
}
You forgot to index the Data property.
const population = JSON.parse(xhr.responseText).Data;
for (const key in population) {
console.log(`${key}: ${population[key]}`);
}

NodeJS hendt/ebay-api / getOrders / Error - Insufficient permissions to fulfill the request

So I am using the hendt/ebay-api library but having no success with the getOrders call.
Here's the auth scopes I'm using when setting the ORIGINAL User access token...:
eBay.auth.oAuth2.setScope([
'https://api.ebay.com/oauth/api_scope',
'https://api.ebay.com/oauth/api_scope/sell.marketing.readonly',
'https://api.ebay.com/oauth/api_scope/sell.marketing',
'https://api.ebay.com/oauth/api_scope/sell.inventory.readonly',
'https://api.ebay.com/oauth/api_scope/sell.inventory',
'https://api.ebay.com/oauth/api_scope/sell.account',
'https://api.ebay.com/oauth/api_scope/sell.account.readonly',
'https://api.ebay.com/oauth/api_scope/sell.fulfillment.readonly',
'https://api.ebay.com/oauth/api_scope/sell.fulfillment',
'https://api.ebay.com/oauth/api_scope/sell.analytics.readonly',
'https://api.ebay.com/oauth/api_scope/sell.finances',
'https://api.ebay.com/oauth/api_scope/sell.payment.dispute',
'https://api.ebay.com/oauth/api_scope/commerce.identity.readonly',
]);
Here's my code (ExpressJS backend controller method...):
exports.getOrders = async (req, res) => {
let _id = req.params.userId; // user's _id
let token = await refreshEbayToken(_id, eBay)
console.log(`token...`, token) // not an array! It's an object!
// set OAuth2 eBay credentials
eBay.auth.oAuth2.setCredentials(token.access_token);
try {
let result = await eBay.sell.fulfillment.getOrders({
filter: 'orderfulfillmentstatus:{NOT_STARTED|IN_PROGRESS}',
limit: 5
})
console.log(`Got a result...`, result)
res.json(result)
} catch (e) {
console.log(`Got an error in getOrders...`, e)
res.status(400).json( { error: e } )
}
}
Here's the error I get:
{
"meta": {
"errors": [
{
"errorId": 1100,
"domain": "ACCESS",
"category": "REQUEST",
"message": "Access denied",
"longMessage": "Insufficient permissions to fulfill the request."
}
]
},
"name": "EBayAccessDenied"
}
Even freshly minted User access tokens through those scopes get this error.
According to the ebay docs on getOrders, these are the required auth scopes for this call:
https://api.ebay.com/oauth/api_scope/sell.fulfillment
https://api.ebay.com/oauth/api_scope/sell.fulfillment.readonly
Upon further investigation, I found I am certainly using those scopes in the response (below is a snippet of the scopes grabbed from the larger ebay error)...
...%20https%3A%2F%2Fapi.ebay.com%2Foauth%2Fapi_scope%2Fsell.fulfillment.readonly%20https%3A%2F%2Fapi.ebay.com%2Foauth%2Fapi_scope%2Fsell.fulfillment%20https%3A%2F%2Fapi.ebay.com%2Foauth%2Fapi_scope%2Fsell.analytics.readonly%20https%3A%2F%2Fapi.ebay.com%2Foauth%2Fapi_scope%2Fsell.finances%20...
As shown above, I am clearly using the sell.fulfillment and sell.fulfillment.readonly scopes so I do not understand what is the issue.
What do you think could be the issue?
So I am using the library but having no success with the getOrders call.
Here's the auth scopes I'm using when setting the ORIGINAL User access token
https://gist.github.com/mudassaralichouhan/d952b464b2907c7f833c87c05152eb76
I finally got it working.
Here is an example of what I receive now:
{
"sales": [
{
"orderId": "xxxxxxxxx",
"legacyOrderId": "xxxxxxxxx-xxxxxxxxx",
"creationDate": "2022-03-09T23:10:36.000Z",
"lastModifiedDate": "2022-03-18T15:51:04.000Z",
"orderFulfillmentStatus": "FULFILLED",
"orderPaymentStatus": "PAID",
"sellerId": "xxxx",
"buyer": {
"username": "xxxxx",
"taxAddress": {
"stateOrProvince": "xx",
"postalCode": "xxxxxxxx",
"countryCode": "xx"
}
},
"pricingSummary": {
"priceSubtotal": {
"value": "xxxxx",
"currency": "USD"
},
"deliveryCost": {
"value": "0.0",
"currency": "USD"
},
"total": {
"value": "xxxxx",
"currency": "USD"
}
},
"cancelStatus": {
"cancelState": "NONE_REQUESTED",
"cancelRequests": []
},
"paymentSummary": {
"totalDueSeller": {
"value": "xxxxx",
"currency": "USD"
},
"refunds": [],
"payments": [
{
"paymentMethod": "EBAY",
"paymentReferenceId": "xxxxxx",
"paymentDate": "2022-03-09T23:15:33.109Z",
"amount": {
"value": "xxxxxxxx",
"currency": "USD"
},
"paymentStatus": "PAID"
}
]
},
"fulfillmentStartInstructions": [
{
"fulfillmentInstructionsType": "SHIP_TO",
"minEstimatedDeliveryDate": "2022-03-14T07:00:00.000Z",
"maxEstimatedDeliveryDate": "2022-03-19T07:00:00.000Z",
"ebaySupportedFulfillment": false,
"shippingStep": {
"shipTo": {
"fullName": "xxxxxxxxxx",
"contactAddress": {
"addressLine1": "xxxxxxxxxxx",
"city": "xxxxxxxxxx",
"stateOrProvince": "xx",
"postalCode": "xxxxxxxxx",
"countryCode": "US"
},
"primaryPhone": {
"phoneNumber": "xxxxxxxxxxxxx"
},
"email": "xxxxxxxxxxxx#members.ebay.com"
},
"shippingServiceCode": "ShippingMethodStandard"
}
}
],
"fulfillmentHrefs": [
"https://api.ebay.com/sell/fulfillment/v1/order/xxxxxxxxxxx/shipping_fulfillment/xxxxxxxxxx"
],
"lineItems": [
{
"lineItemId": "xxxxxxxxxx",
"legacyItemId": "xxxxxxxxxx",
"legacyVariationId": "xxxxxxxxxx",
"sku": "xxxxxxxxxx",
"title": "xxxxxxxxxx",
"lineItemCost": {
"value": "xxxxxxxxxx",
"currency": "USD"
},
"quantity": 1,
"soldFormat": "FIXED_PRICE",
"listingMarketplaceId": "EBAY_US",
"purchaseMarketplaceId": "EBAY_US",
"lineItemFulfillmentStatus": "FULFILLED",
"total": {
"value": "xxxxxxxxxx",
"currency": "USD"
},
"deliveryCost": {
"shippingCost": {
"value": "0.0",
"currency": "USD"
}
},
"appliedPromotions": [],
"taxes": [],
"ebayCollectAndRemitTaxes": [
{
"taxType": "STATE_SALES_TAX",
"amount": {
"value": "xxxxxxxxxx",
"currency": "USD"
},
"collectionMethod": "NET"
}
],
"properties": {
"buyerProtection": true
},
"lineItemFulfillmentInstructions": {
"minEstimatedDeliveryDate": "2022-03-14T07:00:00.000Z",
"maxEstimatedDeliveryDate": "2022-03-19T07:00:00.000Z",
"shipByDate": "2022-03-14T06:59:59.000Z",
"guaranteedDelivery": false
},
"itemLocation": {
"location": "xxxxxxxxxx",
"countryCode": "US",
"postalCode": "xxxxxxxxxx"
}
}
],
"ebayCollectAndRemitTax": true,
"salesRecordReference": "xxxxxxxxxx",
"totalFeeBasisAmount": {
"value": "xxxxxxxxxx",
"currency": "USD"
},
"totalMarketplaceFee": {
"value": "xxxxxxxxxx",
"currency": "USD"
}
}
]
}
Here are my scopes:
eBay.auth.oAuth2.setScope([
'https://api.ebay.com/oauth/api_scope',
'https://api.ebay.com/oauth/api_scope/sell.marketing.readonly',
'https://api.ebay.com/oauth/api_scope/sell.marketing',
'https://api.ebay.com/oauth/api_scope/sell.inventory.readonly',
'https://api.ebay.com/oauth/api_scope/sell.inventory',
'https://api.ebay.com/oauth/api_scope/sell.account',
'https://api.ebay.com/oauth/api_scope/sell.account.readonly',
'https://api.ebay.com/oauth/api_scope/sell.fulfillment.readonly',
'https://api.ebay.com/oauth/api_scope/sell.fulfillment',
'https://api.ebay.com/oauth/api_scope/sell.analytics.readonly',
'https://api.ebay.com/oauth/api_scope/sell.finances',
'https://api.ebay.com/oauth/api_scope/sell.payment.dispute',
'https://api.ebay.com/oauth/api_scope/commerce.identity.readonly',
]);
Here is the code getting it right ( express.js )...
exports.getOrders = async (req, res) => { // https://developer.ebay.com/Devzone/XML/docs/Reference/eBay/GetOrders.html
let _id = req.params.userId; // user's _id
let a = {}
a._id = _id
a.userDoc = await User.findById( { _id: a._id } )
eBay.auth.oAuth2.setCredentials( a.userDoc.token[ 0 ] ) // set OAuth2 eBay credentials
try
{
a.result = await eBay.trading.getOrders({
filter: 'orderfulfillmentstatus:{NOT_STARTED|IN_PROGRESS}',
limit: 5
})
console.log(`Got a result...`, a.result)
} catch ( e ) {
}
}
I send in the mongodb user _id as request params and use that to pull out their user token, which is passed into eBay.auth.oAuth2.setCredentials( a.userDoc.token[ 0 ] ) and allows the call to actually be made... eBay.trading.getOrders
I hope this helps someone out there. I remember being unable to make this call for months.

Remote method in LoopBack not being called

When calling a remote method in my LoopBack project, it seems to only return an empty array. I don't think it is really being called at all but perhaps the default implementation is being called.
member.js
module.exports = function(Member) {
Member.getProjectsForMember = function(id, callback) {
console.error('HERE');
return callback(null, {'test': '123'});
};
};
member.json
{
"name": "member",
"base": "User",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"name": {
"type": "string",
"required": true
}
},
"validations": [],
"relations": {
"projects": {
"type": "hasMany",
"model": "project",
"options": {
"nestRemoting": false
}
}
},
"acls": [{
"accessType": "*",
"principalType": "ROLE",
"principalId": "$authenticated",
"permission": "ALLOW"
},
{
"accessType": "*",
"principalType": "ROLE",
"principalId": "$unauthenticated",
"permission": "DENY"
}
],
"methods": {
"getProjectsForMember": {
"accepts": [{
"arg": "id",
"type": "number",
"required": true,
"http": {
"source": "path"
}
}],
"returns": [{
"arg": "projects",
"type": "Object",
"root": true,
}],
"http": [{
"path": "/:id/projects",
"verb": "get"
}]
}
}
}
I am calling it using the LoopBack API Explorer via a GET to /members/{id}/projects:
http://localhost:3000/api/members/3e26u0aa62155715vcb52afa/projects?access_token=R6GKVHwFuMG2caJexuyoMd0JSNOWtvLVXIEmRj1IkNSrM54bwomQLxHcpqlyFaHk
The response is []. I would expect to see the response of {'test': '123'} and the 'HERE' logged to the terminal but I do not.

How to transform api response in nestjs?

I am using Nest Serialization to transform api response. However, it returns really crypic result. I expect it to slice some fields out of the data but for some reason, it shows weird result.
product.entity.js
export class ProductEntity {
id: string
description: string
status: boolean
price: string
moq: number
rating: number
last_modified: string
constructor(partial: Partial<ProductEntity>) {
Object.assign(this, partial)
}
}
product.controller.ts
#UseInterceptors(ClassSerializerInterceptor)
#Get()
async findAll(
#Query('page') page: number,
#Query('per_page') per_page: number
): Promise<ProductEntity[]> {
if (!page && !per_page) {
throw new BadRequestException('Proper query params not supplied')
}
const data: ProductEntity[] = []
const products: any = await this.productService.findAll({
page,
per_page
})
products.map(product => {
data.push(new ProductEntity(product))
})
return data
}
product.service.ts
async findAll(query): Promise<Product[]> {
const { page, per_page }: { page: number; per_page: number } = query
const from: number = (page - 1) * per_page
return this.productModel
.find()
.skip(from)
.limit(Number(per_page))
}
which returns,
"$__": {
"strictMode": true,
"selected": {},
"getters": {},
"_id": {
"_bsontype": "ObjectID",
"id": {
"type": "Buffer",
"data": [
93,
15,
149,
140,
78,
148,
77,
10,
10,
105,
51,
130
]
}
},
"wasPopulated": false,
"activePaths": {
"paths": {
"moq_type": "init",
"moq": "init",
"price_type": "init",
"price": "init",
"name": "init",
"category_id": "init",
"company_id": "init",
"short_description": "init",
"long_description": "init",
"active": "init",
"variations": "init",
"keywords": "init",
"photos": "init",
"_id": "init",
"created_at": "init",
"updated_at": "init",
"__v": "init"
},
"states": {
"ignore": {},
"default": {},
"init": {
"_id": true,
"short_description": true,
"long_description": true,
"active": true,
"variations": true,
"keywords": true,
"photos": true,
"name": true,
"price": true,
"price_type": true,
"moq": true,
"moq_type": true,
"category_id": true,
"company_id": true,
"created_at": true,
"updated_at": true,
"__v": true
},
"modify": {},
"require": {}
},
"stateNames": [
"require",
"modify",
"init",
"default",
"ignore"
]
},
"pathsToScopes": {},
"cachedRequired": {},
"session": null,
"$setCalled": [],
"emitter": {
"_events": {},
"_eventsCount": 0,
"_maxListeners": 0
},
"$options": {
"skipId": true,
"isNew": false,
"willInit": true
}
},
Am I doing something wrong in here or is it not correct way to transform API response?
Not sure about NestJS but in regular node.js for mongodb, If you are calling find() that way X().X().X() you need to add at the end of the pipeline the call to exec() method, like :
this.productModel
.find()
.skip(from)
.limit(Number(per_page))
.exec();
I am getting that too. The answer is removed #UseInterceptors(ClassSerializerInterceptor) in your controller.
Maybe that function utilize object inheritance from class extension? I think you don't really need it because that function is used to cast a response (like tranforming camerCase to snake_case, etc). If you really need it, then I don't know because I am still strugle with it too.

Loopback external api errors

I have created my external api on loopback, i tried to use the Model.find method and other query methods, it not working for me, what i get is just error message.
Below are the message i get
the error i get
After i check it might be my api result problem, because my object is inside another object.
my api output
Can some guide me how to solve it, can change the output result?
datasources.js
"consumer_model": {
"name": "consumer_model",
"connector": "rest",
"debug": "false",
"operations": [
{
"template": {
"method": "GET",
"url": "http://myurl.com/api/v1/consumers",
"headers": {
"accepts": "application/json",
"content-type": "application/json"
},
"query": {
"id": "{id}",
"firstname": "{firstname}"
},
"responsePath": "$.data"
},
"functions": {
"consumer": [
"id",
"firstname"
]
}
}
]
}
model-config.js
"consumers": {
"dataSource": "consumer_model",
"public": true
}
myconsumer.js
module.exports = function(consumers) {
};
myconsumer.json
{
"name": "consumers",
"base": "Model",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {},
"validations": [],
"relations": {},
"acls": [],
"methods": {}
}

Categories

Resources