About badly documented patreon-js - javascript

I don't understand this documentation, I tried so hard to do the mentioned info below but I am not quite sure what "jsonApiURL" is. Can someone tell me how to properly achieve the goal in the quote.
Response Format
You can request specific related resources and or resource attributes
that you want returned by our API, as per the JSON:API specification.
The lists of valid includes and fields arguments are provided in
patreon/schemas. For instance, if you wanted to request the total
amount a patron has ever paid to your campaign, which is not included
by default, you could do:
const patreonAPIClient = patreonAPI(access_token)
const url = jsonApiURL(`/current_user`, {
fields: {
pledge: [...pledge_schema.default_attributes, pledge_schema.attributes.total_historical_amount_cents]
}
})
patreonAPIClient(url, callback)
More info below
https://github.com/Patreon/patreon-js

Related

Error with AWS SDK-JS API when Retrieving Seller Partner Product Catalog Inventory

I need to retrieve the product catalog of my seller partner on Amazon. Although the API refers to this as "Inventory," I couldn't find this term in the SDK documentation. I assume that the "Catalog" namespace is the equivalent.
Update:
My custom application requires a list of the following product values:
ASINs
UPCs
SKUs
FNSKUs
I have read the documentation and found an API that returns what I need, which can be found here:
https://developer-docs.amazon.com/sp-api/docs/fba-inventory-api-v1-use-case-guide
According to the documentation, I need to create a signature in order to use the API. However, it is noted that if I use the AWS SDK, I do not need to calculate the signature myself. Therefore, I understand that the best practice is to use the AWS SDK.
I have the necessary IAM role permissions and the SP-API app has been published. I am currently attempting to use the AWS SDK.
I have made some changes based on recommendations, but I am not completely sure what else I need to do. Here is my current code:
```
export const /*bundle */ start = async () => {
const client = new MarketplaceCatalogClient({
region: REGION,
credentials: {
accessKeyId: ACCESS_KEY_ID,
secretAccessKey: ACCESS_SECRET_KEY,
},
});
const params = {
/** input parameters */
};
const answer = await client.send(
new ListEntitiesCommand({ Catalog: "AWSMarketplace", EntityType: "ContainerProduct" })
);
console.log(100, answer);
return answer;
};
```
I got the next answer with "AmiProduct" or "ContainerProduct":
{
'$metadata': {
httpStatusCode: 200,
requestId: '91fc5fed-6cdc-42d6-97ec-1ed3cc9d5796',
extendedRequestId: undefined,
cfId: undefined,
attempts: 1,
totalRetryDelay: 0
},
EntitySummaryList: []
}
I'm having difficulty understanding how to correctly implement this. Any guidance would be greatly appreciated.
The docs should be better. I spent a good 15 mins on the docs at https://docs.aws.amazon.com/marketplace-catalog/latest/api-reference/welcome.html and failed to find a full list of valid EntityType values.
Some EntityType values are documented here: https://docs.aws.amazon.com/marketplace-catalog/latest/api-reference/seller-products.html
AmiProduct
ContainerProduct
It looks like these types correspond to the product types in the index of the seller guide here -> https://docs.aws.amazon.com/marketplace/latest/userguide/machine-learning-products.html. It's not clear what the other valid values are.
Some other EntityType values are documented here: https://docs.aws.amazon.com/marketplace-catalog/latest/api-reference/private-marketplace.html
Experience
Procurement Policy
It looks the way to go for now is to scrounge these valid values from examples in the docs https://docs.aws.amazon.com/marketplace-catalog/latest/api-reference/welcome.html. Not the best developer experience :grimace:
Assuming you are a seller, that you have registered successfully with your AWS account. You can then use Marketplace APIs.
To use them, you have to create an IAM role or a user with policies to grant access to invoke the selected APIs like listEntities, describeEntity, etc.
Here I again assume you have the Cognito authorized credentials if using AWS SDK.
Now to view the list of products successfully published, you use listEntites command.
You can only view AMI or Containter product types. Read here.
It uses minimum two required parameters Catalog and EntityType. The former has a fixed value AWSMarketplace, and latter can have a value either AmiProduct or ContainerProduct.
To get a detailed information about a specific product, you use describeEntity command. It takes minimum 2 required parameters Catalog and EntityID.
The former again has a fixed value AWSMarketplace. For latter, you'll obtain it from the listEntites response.

Javascript - Is it possible to use fetch or axios.get with a specific property path?

I am a student, in my 3rd week of learning JavaScript, and today I've been completely roadblocked by something I can't find my way around.
Suppose I have the following:
axios.get("www.examplewebsite.com/api/......")
.then((response)=>{
console.log(response)
})
The json in question contains a tremendous amount of data, and all I need is one url from it. I found the property path of:
data.data.examples[0].example.week3.uri
Is there any way to use axios, or even fetch, to grab that single piece of data?
Unless the API provides that option, the client cannot specify which bits of information are wanted. With a regular REST API you get what the server sends you.
But, you can chain .then() calls if you want to narrow your data down and disregard everything you don't care about:
axios.get("www.examplewebsite.com/api/......")
.then(response => response.data.data.examples[0].example.week3.uri)
.then(uri => {
console.log(uri)
})
Or, if you want to grab the URI from the same path for all your examples, you could narrow it down to an array of URIs:
axios.get("www.examplewebsite.com/api/......")
.then(response => response.data.data.examples)
.then(examples => examples.map(item => item.example.week3.uri))
.then(uris => {
console.log(uris)
})
It depends on the server and the backend. It might be possible to get the value, but you have to provide the required information in your request (URL).
For example, this URL (http://site.come/moives) can give you a list of movies, but this (http://site.come/moives/movieid) can give you information about a certain movie. Again it depends on the server ...

Gatsby/React - Get Referring Url

Building a jobs board. Need to know if the user clicked on our link from monster.com, jobs.com, foobar.com, etc. This needs to happen in the code, as I need to send it to an API.
What is the best way to accomplish this?
I tried searching around, but can only find articles on internal routing, e.g.:
How to get previous url in react gatsby
If I need to do this in plain Javascript (not available "out-of-the-box"), please point me in the right direction there too. Not even sure what to google for this other than "UTM parameters". We are using Google Analytics and the marketing team is including utm params in the links, if that helps.
In gatsby each page component has a location prop with some useful info. So you could do something like:
import React from "react"
const IndexPage = ({ location }) => {
console.log(location.search.split("?")[1].split("&"))
return (
<div>
My homepage
</div>
)
}
export default IndexPage
So visiting https://myapp.com/?campaign=foo&id=bar would log ["campaign=foo", "id=bar"]. With that info, you could decide how and when to communicate with your APIs to log the relevant info.
This question was very vague, because I did not understand what I was asking when I posted it. There is two scenarios here that should help you get started. If you have specific questions, follow up - I will try to help.
Scenario 1 (will most likely NOT work, but here for completeness): You are getting referrals from websites you are not at all associated with. For example, you run mycoolsite.com and someone at someforum.com linked to you. The ONLY way you are going to be able to know this without anything additional is if someforum.com sends something called a Referer Request Header. Many popular sites do not.
Scenario 2: Your marketing team pays someone to link to you for a specific promotion. E.g., your marketing team tells someforum.com to link mycoolsite.com for money or as a favor. In this case, they can request that scenario 1 be followed OR, more likely, they can include something called utm params, e.g. when they send the link it's not mycoolsite.com?utm_campaign=monster&utm_source=monsterjobs
When the request comes in to your site, you can then pull these utm params out, to identify which campaign is working.
The code for that looks something like this:
function buildUtmInfoString(currentUrlString) {
const url = new URL(currentUrlString);
let referrerString = '';
utmParamNames.forEach(paramName => {
const paramValue = url.searchParams.get(paramName.standard);
if(!paramValue) {
return;
}
const paramString = `${paramName.colloquial}: ${paramValue}, `;
referrerString += paramString;
});
referrerString = referrerString.substring(0, referrerString.length-2);
return referrerString;
}
Note that you might need to look up utm param standard names, they are supported by Google Analytics out of the box, if your company uses that, but you can use them without GA.
const standardUtmParamNames = {
SOURCE: 'utm_source',
MEDIUM: 'utm_medium',
CAMPAIGN: 'utm_campaign',
TERM: 'utm_term',
CONTENT: 'utm_content'
};
const utmParamNames = [
{
standard: standardUtmParamNames.SOURCE,
colloquial: 'Source'
},
{
standard: standardUtmParamNames.MEDIUM,
colloquial: 'Medium'
},
{
standard: standardUtmParamNames.CAMPAIGN,
colloquial: 'Campaign'
},
{
standard: standardUtmParamNames.TERM,
colloquial: 'Term'
},
{
standard: standardUtmParamNames.CONTENT,
colloquial: 'Content'
}
];
export default utmParamNames;
Note that there are also hacks to accomplish this, but they are not reliable and can be seen as abuse of your user's privacy, so they aren't viable business solutions and I don't recommend wasting time on them.

Meteor: Best practice for modifying document data with user data

Thanks for looking at my question. It should be easy for anyone who has used Meteor in production, I am still at the learning stage.
So my meteor setup is I have a bunch of documents with ownedBy _id's reflecting which user owns each document (https://github.com/rgstephens/base/tree/extendDoc is the full github, note that it is the extendDoc branch and not the master branch).
I now want to modify my API such that I can display the real name of each owner of the document. On the server side I can access this with Meteor.users.findOne({ownedBy}) but on the client side I have discovered that I cannot do this due to Meteor security protocols (a user doesnt have access to another user's data).
So I have two options:
somehow modify the result of what I am publishing to include the user's real name on the server side
somehow push the full user data to the clientside and do the mapping of the _id to the real names on the clientside
what is the best practice here? I have tried both and here are my results so far:
I have failed here. This is very 'Node' thinking I know. I can access user data on clientside but Meteor insists that my publications must return cursors and not JSON objects. How do I transform JSON objects into cursors or otherwise circumvent this publish restriction? Google is strangely silent on this topic.
Meteor.publish('documents.listAll', function docPub() {
let documents = Documents.find({}).fetch();
documents = documents.map((x) => {
const userobject = Meteor.users.findOne({ _id: x.ownedBy });
const x2 = x;
if (userobject) {
x2.userobject = userobject.profile;
}
return x2;
});
return documents; //this causes error due to not being a cursor
}
I have succeeded here but I suspect at the cost of a massive security hole. I simply modified my publish to be an array of cursors, as below:
Meteor.publish('documents.listAll', function docPub() {
return [Documents.find({}),
Meteor.users.find({}),
];
});
I would really like to do 1 because I sense there is a big security hole in 2, but please advise on how I should do it? thanks very much.
yes, you are right to not want to publish full user objects to the client. but you can certainly publish a subset of the full user object, using the "fields" on the options, which is the 2nd argument of find(). on my project, i created a "public profile" area on each user; that makes it easy to know what things about a user we can publish to other users.
there are several ways to approach getting this data to the client. you've already found one: returning multiple cursors from a publish.
in the example below, i'm returning all the documents, and a subset of all the user object who own those documents. this example assumes that the user's name, and whatever other info you decide is "public," is in a field called publicInfo that's part of the Meteor.user object:
Meteor.publish('documents.listAll', function() {
let documentCursor = Documents.find({});
let ownerIds = documentCursor.map(function(d) {
return d.ownedBy;
});
let uniqueOwnerIds = _.uniq(ownerIds);
let profileCursor = Meteor.users.find(
{
_id: {$in: uniqueOwnerIds}
},
{
fields: {publicInfo: 1}
});
return [documentCursor, profileCursor];
});
In the MeteorChef slack channel, #distalx responded thusly:
Hi, you are using fetch and fetch return all matching documents as an Array.
I think if you just use find - w/o fetch it will do it.
Meteor.publish('documents.listAll', function docPub() {
let cursor = Documents.find({});
let DocsWithUserObject = cursor.filter((doc) => {
const userobject = Meteor.users.findOne({ _id: doc.ownedBy });
if (userobject) {
doc.userobject = userobject.profile;
return doc
}
});
return DocsWithUserObject;
}
I am going to try this.

How do I access the data given in the onHttpRequest function in the Firefox Add-on SDK?

I am trying to read the response headers 'name' and 'value'. The end goal is to compare them to some pre-set name and a value to see if they match.
Here is what I have so far, it's the function that run every time I get a response header.
var observer = require("observer-service");
observer.add("http-on-examine-response", onHttpRequest);
function onHttpRequest(subject, data)
{
console.log("request subject...." + subject);
console.log("request data...." + data);
}
The output is as follows:
request subject....[xpconnect wrapped nsISupports]
request data....null
I was hoping to know how to get the rest of the data out of the response.
Any help would be great, thanks.
The subject for http-on-examime-response implements nsIHttpChannel, among some other things. You may use .QueryInterface() or instanceof (which internally kinda uses QueryInteface, so that this works as well) to get to that interface.
const {Ci} = require("chrome");
if (subject instanceof Ci.nsIHttpChannel) {
console.log("content-type", subject.getResponseHeader("content-type"));
subject.visitResponseHeaders(function(header, value) {
console.log(header, value);
});
}
There are a couple of other questions around here going into more detail on how to use these notifications... Also, mxr can help a lot checkout out what interfaces there are, how it fits together and how one could use it (in particular the existing tests are great to see some uses for all kinds of stuff).
There is also the "nsITraceableChannel, Intercept HTTP Traffic" article going into more details, e.g. on how to use nsITraceableChannel to get the payload data from such a channel.

Categories