Select Operator in the Contentful SDK - contentful

How can I use the Contentful Select Operator in the Javascript SDK, to only select the property: fields?
The GET request in the documentation looks like this
GET https://cdn.contentful.com/spaces/<space-id>/entries/?select=fields

const contentful = require('contentful')
const client = contentful.createClient({
space: '<space_id>',
accessToken: '<content_delivery_api_key>'
})
client.getEntries({
content_type: '<content_type_id>',
select: 'sys.id,fields.<field_name>'
})
.then((response) => console.log(response.items))
.catch(console.error)

Related

how can i create a rest api with a key system? and json

I try to make my api.
it should look like this:
http://test.com/api/genpw/KEY=key/TYPE=BASE64/HEX
the request should come back like this:
{
APIKEY: "KEY",
TYPE: "BASE64 / HEX"
PASSWORD: "GENERATED PW"
}
How do I do this and how can I do this?
I don't think these parameters should be part of the URL. Following the REST API standard, they should be query parameters and the URL must be: http://test.com/api/genpw?key=some-value&type=base64
Example how to get query parameters in express:
app.get('/api/content', async (req, res) => {
const {key, type, password} = req.query;
res.send('success');
}

Nodejs Error : " User does not have sufficient permissions for this profile "

I have a Nodejs code that runs queries on the Google Analytics API, I'm using the googleapis library for authentication and getting data.
But my problem occurs when I try to send queries to retrieve "page views" for example, but in the end, I get an error.
therefore, I had added the client_email for my service account to the Google Analytics.
NodeJS Code :
const scopes = ['https://www.googleapis.com/auth/analytics.readonly']
const jwt = new google.auth.JWT(keys.client_id, null, keys.private_key, scopes)
async function getData() {
const response = await jwt.authorize()
const result = await google.analytics('v3').data.ga.get({
'auth': jwt,
'ids': 'ga:146850375',
'start-date': '30daysAgo',
'end-date': 'today',
'metrics': 'ga:pageviews'
}).then( (res) => console.log(res) )
.catch( (e) => console.error(e) )
console.dir(result)
}
getData()
Results :
[1] : https://i.stack.imgur.com/zWJZm.png
Solution :
Actually, the Account Id (under Admin -> Account -> Account Settings) is not the correct number to use as your Profile Id. You have to use the specific View Id that you want to analyse. These may be the same (sometimes), but they may also be different, as it is my case.

Rendering Current Page With PhantomJS

I am building an analytics dashboard using the MERN stack (Express, Node) are the Important things to highlight.
As part of a dash view, I was trying to find if it's possible to trigger a PhantomJS call to create a pdf report using a button on the page itself.
Given you need to be logged in to see your own analytics, I can not just run phantom from the command line and pass it in the URL of one of the dashboard pages since it requires a login and queries to be made.
Is it possible to do this with phantomJS?
If I correctly understood your question.
Example:
[main.js]
const dashboardToPdfCtrl = require("./controllers/phantom/pdf");
router.route("/api/dashboard/phantom").post(dashboardToPdfCtrl.createPdf);
router.route("/api/dashboard/phantom/html")
.post(dashboardToPdfCtrl.createDashboard);
When the user clicks on the "button" you can validate the USER according to the architecture of your application.
[pdf.js]
exports.createPdf= async (req, res) => {
if (!req.user || !req.user.sub) {
return res
.status(401)
.send({ message: 'No authorization token was found' });
}
const instance = await phantom.create();
const page = await instance.createPage();
const settings = {
operation: "POST",
encoding: "utf8",
headers: {
"Content-Type": "application/json"
},
data: JSON.stringify({
user: req.body.userId,
anyDataYouNeedToRender: req.body.anyDataYouNeedToRender
})
};
//POST request to /api/dashboard/phantom/html
await page.open(
`${process.env.HOST}:${
process.env.PORT
}/api/dashboard/phantom/html`,
settings
);
//Save the content of /public/dashboard/dashboard.html with received data to pdf
const pageSaved = await page.render(
path.resolve(`./public/dashboard/file.pdf`)
);
if (pageSaved) await instance.exit();
}
exports.createDashboard = (req, res) => {
res.render(
path.resolve("./public/dashboard/dashboard.html"),
{ user: req.body.user,
anyDataYouNeedToRender: req.body:anyDataYouNeedToRender
}
);
};
Is that what you were looking for? I want to help you, feel free to ask detalization.
P.S. As friends told before in comments, it will be great if you give us more information to understend you goal.

Calling users from angular to node (MEAN) is sending only email and _id to angular

I'm using the following code ..
// Node.js
router.get('/users/all', authenticate, (req, res) => {
User.find({some query}).select('firstName lastName email').then((users) => {
res.send(users);
});
//Angular Service
let opts = { headers: this.getCommonHeaders(), params: new HttpParams() };
return this.http.get(getUserDataUrl, opts)
.pipe(
map(response => {
// here is the problem
console.log(response.json());
return response.json()
}),
catchError(this.handleErrors)
);
In the opts headers I have mentioned the data type:
getCommonHeaders() {
return new HttpHeaders({
'Content-Type': 'application/json',
'x-auth': this.getToken()
})
}
In the console.log(response.json()) I'm getting only email and _id in the array's object. Adding the same console.log(user) on node.js before res.send(user) is showing the entire data with firstName and lastName
Then I added .lean() to the User function. this allowed the rest of the firstName and lastName to appear. How do I get the entire data without converting them to plain objects?
To me it seems like this is the problem. When you use find() method in mongoose, It gives an array. so you convert that array into json and send using res.send(). so when you access it using Angular. it may be crashing and not giving the correct format so try changing the code in node js like this.
Instead of find() try using findOne() in mongoose like this. I assume you only intend to take one user from this query right ?
// Node.js
router.get('/users/all', authenticate, (req, res) => {
User.findOne({some query}).select('firstName lastName email').then((user) => {
res.send(user); // there was a typo I changed it too. look in the question not user it was users.
});
Try to use res.json("JSON Object"); instead of res.send()..
Else try to check the db using tool like robomongo

How to make an uptime command in nodejs tmijs chat bot

How would you make an uptime command with tmi.js, I thought it would be as simple as;
client.on("chat", function(channel, user, message, self, uptime){
client.say("CHANNEL", "Channel has been live for " + uptime
})
How would you go about making this command, the example I gave does not work and I would request you to let me know.
It doesn't look like channel metadata is available over the Twitch WebSocket API. If you want to get that information, you'll need to go through the "New Twitch API" and use the /streams endpoint.
You will also need to have a Client-ID to make requests to this endpoint. You can get one by following the instructions here: Apps & Authentication Guide.
Once you have a Client-ID, you can make a request. I'm using the node-fetch module to make requests easier. This example will get the 2 most active streams. You can adjust the query string parameters to get the appropriate stream.
const querystring = require("querystring"),
fetch = require("node-fetch");
const CLIENT_ID = "YOUR_CLIENT_ID";
const STREAMS_URL = "https://api.twitch.tv/helix/streams";
const qs = querystring.stringify({
first: 2
});
const qUrl = `${STREAMS_URL}?${qs}`;
const fetchArgs = {
headers: {
"Client-ID": CLIENT_ID
}
};
fetch(qUrl, fetchArgs)
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err));
This would print out something like the following:
{
data: [{
id: '28378863024',
user_id: '19571641',
game_id: '33214',
community_ids: [],
type: 'live',
title: 'Morning Stream! | #Ninja on Twitter and Insta ;)',
viewer_count: 107350,
started_at: '2018-04-18T14:58:45Z',
language: 'en',
thumbnail_url: 'https://static-cdn.jtvnw.net/previews-ttv/live_user_ninja-{width}x{height}.jpg'
},
{
id: '28379115264',
user_id: '22859264',
game_id: '32399',
community_ids: [Array],
type: 'live',
title: 'LIVE: Astralis vs. Space Soldiers - BO1 - CORSAIR DreamHack Masters Marseille 2018 - Day 1',
viewer_count: 54354,
started_at: '2018-04-18T15:28:44Z',
language: 'nl',
thumbnail_url: 'https://static-cdn.jtvnw.net/previews-ttv/live_user_dreamhackcs-{width}x{height}.jpg'
}]
}
The started_at property is the timestamp of when the stream began. Bear in mind that this API is rate limited so you should probably cache the started_at so you don't immediately run out of requests.

Resources