Is any library of nodejs work with GitHub API v4 exist? - node.js

Thank you guys cause reading my question. The title is exactly what i wanna known.
Hope it do not cost your time much.

Some of the most common graphql client are graphql.js and apollo-client. You can also use the popular request module. The graphql API is a single POST endpoint on https://api.github.com/graphql with a JSON body consisting of the query fields and the variables fields (if you have variables in the query)
Using graphql.js
const graphql = require('graphql.js');
var graph = graphql("https://api.github.com/graphql", {
headers: {
"Authorization": "Bearer <Your Token>",
'User-Agent': 'My Application'
},
asJSON: true
});
graph(`
query repo($name: String!, $owner: String!){
repository(name:$name, owner:$owner){
createdAt
}
}
`)({
name: "linux",
owner: "torvalds"
}).then(function(response) {
console.log(JSON.stringify(response, null, 2));
}).catch(function(error) {
console.log(error);
});
Using apollo-client
fetch = require('node-fetch');
const ApolloClient = require('apollo-client').ApolloClient;
const HttpLink = require('apollo-link-http').HttpLink;
const setContext = require('apollo-link-context').setContext;
const InMemoryCache = require('apollo-cache-inmemory').InMemoryCache;
const gql = require('graphql-tag');
const token = "<Your Token>";
const authLink = setContext((_, {
headers
}) => {
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : null,
}
}
});
const client = new ApolloClient({
link: authLink.concat(new HttpLink({
uri: 'https://api.github.com/graphql'
})),
cache: new InMemoryCache()
});
client.query({
query: gql `
query repo($name: String!, $owner: String!){
repository(name:$name, owner:$owner){
createdAt
}
}
`,
variables: {
name: "linux",
owner: "torvalds"
}
})
.then(resp => console.log(JSON.stringify(resp.data, null, 2)))
.catch(error => console.error(error));
Using request
const request = require('request');
request({
method: 'post',
body: {
query: `
query repo($name: String!, $owner: String!){
repository(name:$name, owner:$owner){
createdAt
}
} `,
variables: {
name: "linux",
owner: "torvalds"
}
},
json: true,
url: 'https://api.github.com/graphql',
headers: {
Authorization: 'Bearer <Your Token>',
'User-Agent': 'My Application'
}
}, function(error, response, body) {
if (error) {
console.error(error);
throw error;
}
console.log(JSON.stringify(body, null, 2));
});

Related

Having trouble sending data through axios in Nodejs

When I try to send data via axios with query data. Looks like the problem is with JSON.stringify, it returns incorrect data to be able to send.
Is there any solution to this problem?
var axios = require('axios');
var data = JSON.stringify({
query: `mutation { flowTriggerReceive(body: "{ \"trigger_id\": \"28a17088-92d7-42e7-a1f2-3594fc4b8bf9\", \"resources\": [ { \"name\": \"AppName\", \"url\": \"https://app.doman.com\" } ], \"properties\": { \"product_id\": 3665695899753, \"Rating\": 5, \"Author\": \"John Kendy\", \"Email\": \"cauhaibg#gmail.com\", \"Country Code\": \"VN\" } }") { userErrors { field, message } } }`,
variables: {}
});
//console.log(data);
var config = {
method: 'post',
url: 'https://{shop_domain}/admin/api/2023-01/graphql.json',
headers: {
'X-Shopify-Access-Token': 'xxxxxxxxxxxxxxxxxxx',
'Content-Type': 'application/json'
},
data : data
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
Get error
{"errors":[{"message":"Parse error on \": \" (STRING) at [1, 51]","locations":[{"line":1,"column":51}]}]}
Note that you do not need to serialize the data object to JSON as Axios will automatically do it for you. Try to send the data object "as is" without stringify it first
var axios = require('axios');
var data = {
query: `mutation { flowTriggerReceive(body: "{ \"trigger_id\": \"28a17088-92d7-42e7-a1f2-3594fc4b8bf9\", \"resources\": [ { \"name\": \"AppName\", \"url\": \"https://app.doman.com\" } ], \"properties\": { \"product_id\": 3665695899753, \"Rating\": 5, \"Author\": \"John Kendy\", \"Email\": \"cauhaibg#gmail.com\", \"Country Code\": \"VN\" } }") { userErrors { field, message } } }`,
variables: {}
};
var config = {
method: 'post',
url: 'https://{shop_domain}/admin/api/2023-01/graphql.json',
headers: {
'X-Shopify-Access-Token': 'xxxxxxxxxxxxxxxxxxx',
'Content-Type': 'application/json'
},
data : data
};

Apollo client does not send headers when used in nodejs environment

I've got a client-side app that uses apollo/client and I'have a few server-side function where also use the client to do some light queries and mutations.
I've recently implemented jwt integration and now my server-side calls fail because of what I presume is missing headers.
here is my client setup:
const wsLink = new GraphQLWsLink(
createClient({
url: process.env.API_URL_WS,
webSocketImpl: isNode ? ws : null,
connectionParams: async () => {
const { id_token } = await auth.getSession();
return {
headers: {
Authorization: `Bearer ${id_token}`,
},
};
},
})
);
const authLink = setContext(async (_, { headers }) => {
const { id_token } = await auth.getSession();
return {
headers: {
...headers,
Authorization: `Bearer ${id_token}`,
},
};
});
const httpLink = new HttpLink({
uri: process.env.API_URL_HTTP,
});
const splitLink = split(
({ query, ...rest }) => {
const definition = getMainDefinition(query);
return (
definition.kind === "OperationDefinition" &&
definition.operation === "subscription"
);
},
wsLink,
authLink.concat(httpLink)
);
export const client = new ApolloClient({
link: splitLink,
cache: new InMemoryCache(),
});
and here is how I am using it in the server-side function to make a mutation
await client
.mutate({
mutation: gql`
mutation InsertSubscriptionId(
$id: uuid!
$stripe_subscription_id: String!
) {
update_user_by_pk(
pk_columns: { id: $id }
_set: { stripe_subscription_id: $stripe_subscription_id }
) {
id
}
}
`,
variables: {
id: session.metadata.hasura_user_id,
stripe_subscription_id: session.subscription,
},
context: {
headers: {
Authorization: req.cookies.access_token,
},
},
})
.then((result) => console.log(result))
.catch(console.log);
this call fails even if I use the users access token or apply an admin token for access to the DB.
As a workaround I've resorted to using fetch for this mutation (which works). Any idea why headers are not respected?
My workaround with admin access secret:
fetch(process.env.API_URL_HTTP, {
method: "POST",
headers: {
"Content-Type": "application/json",
"x-hasura-admin-secret": process.env.GATSBY_HASURA_ADMIN_SECRET,
},
body: JSON.stringify({
query: `
mutation InsertSubscriptionId(
$id: uuid!
$stripe_subscription_id: String!
) {
update_user_by_pk(
pk_columns: { id: $id }
_set: { stripe_subscription_id: $stripe_subscription_id }
) {
id
}
}
`,
variables: {
id: session.metadata.hasura_user_id,
stripe_subscription_id: session.subscription,
},
}),
})
.then((res) => res.json())
.then((result) => console.log(result));
In this case the session was lost after a few jumps between my app and payment provider. As user can't be authenticated when session is lost, I've resorted to authenticate the admin user for this ssr function

How to access and store the token and use it in other requests with Node.js?

I'm using the code below to authenticate myself and get a token.
It works perfectly.
const config = {
headers: { Authorization: 'Bearer ${token}' }
};
const bodyParameters = {
username: "teste",
senha: "123456"
};
axios.post(
'url ...',
bodyParameters,
config
).then(console.log).catch(console.log);
And the token below:
My question is: how to access this token and use it in another request?
For example, to get data from this API.
const config2 = {
headers: { Authorization: `Bearer ${token}` }
};
const bodyParameters2 = {
cpf: "12345",
hash: "912409kskllj1u2ou1p4124821"
};
axios.get(
'url..',
bodyParameters,
config
).then(console.log).catch(console.log);
In this case, I get error: 401 (unauthorized).
--UPDATE--
Update based on interceptors.
var LocalStorage = require('node-localstorage').LocalStorage,
localStorage = new LocalStorage('./scratch');
const api = axios.create({
baseURL: 'http://www.externalapi.com/', // this way you setup the static part of it and just call the instance with the rest of the specific route
});
api.interceptors.request.use(config => {
const token = localStorage.getItem('token');
if (token) {
config.headers['Authorization'] = `Bearer ${token}`;
}
return config;
});
exports.novaSolicitacao = (req, res) => {
const bodyParameters = {
username: "teste",
senha: "123456"
};
api.post(
'/login',
bodyParameters,
).then(console.log).catch(console.log);
const bodyParameters2 = {
cpf: "123456",
aceite: true,
};
app.get(
'/search',
bodyParameters2,
config
).then(console.log).catch(error);
I made this update to the code, but I get this error:
data: {
statusCode: 404,
error: 'SESSIONTOKENEXPIRED',
message: 'O token expirou.'
}
},
isAxiosError: true,
toJSON: [Function: toJSON]

API call works with Postman, but does not with Axios

I am using third party API. The way it works is:
I send post request then Token is returned in response.
Then i use that Token to check status. Afterwards, report is returned in response
In postman, i make both calls separately and it is working, but in Axios I have 1 async function and 2 await Promises.
Postman(NodeJs - Axios) looks like this:
For getting Token:
var data = JSON.stringify({
"security": {
"pLogin": "a",
"pPassword": "io"
},
"data": {
"pHead": "005",
"pCode": "00433",
"pLegal": 1,
"pClaimId": "z4LpXRWZKecSnL-FQtgD",
"pReportId": 8,
"pReportFormat": 1
}
});
var config = {
method: 'post',
url: 'http://10.22.50.10/report/',
headers: {
'Content-Type': 'application/json'
},
data : data
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
For getting Report with the token:
var data = JSON.stringify({
"data": {
"pHead": "005",
"pCode": "00433",
"pToken": "kgqjismxdrpjnjaqnlnbmovcsvnkarfd",
"pClaimId": "z4LpXRWZKecSnL-FQtgD",
"pReportFormat": 1
}
});
var config = {
method: 'post',
url: 'http://10.22.50.10/report/status',
headers: {
'Content-Type': 'application/json'
},
data : data
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
My async function with Axios:
/* 1. Searching for client in database (Full name is used, but can be changed)*/
const client = await client.findOne({
name: body.name,
family_name: body.family_name,
patronymic: body.patronymic
});
if (!client) {
return res.status(401).json({ message: "Client is not registered" });
}
/* 2. If client was found in database, make an API call */
let credit_report;
try{
credit_report = await axios.post(
'http://10.22.50.10/report',
{
security: {
pLogin: 'a',
pPassword: 'io',
},
data: {
pHead: "005",
pCode: "00433",
pLegal: 1,
pClaimId: client.claim_id,
pReportId: 8,
pReportFormat: 1
}
},
{
headers: {
'content-type': 'application/json'
}
}
);
}catch(err){
return res.status(400).json({errorMessage: err.message})
}
// await new Promise(resolve => setTimeout(resolve, 3000));
if(!credit_report.data.data.token) return res.status(400).json({message: credit_report.data});
const credit_report_status = await axios.post(
'http://10.22.50.10/report/status',
{
data: {
pHead: "005",
pCode: "00433",
pToken: credit_report.data.data.token,
pClaimId: client.claim_id,
pReportFormat: 1
}
},
{
headers: {
'content-type': 'application/json'
}
}
);
console.log(credit_report_status)
if(credit_report_status.data.data.result == '05000') return res.status(200).json({ message: 'Client fetched.', clientData64: credit_report_status.data.data.reportBase64});
else return res.status(400).json({message: credit_report_status.data})
When I am using Postman to check my module, it is saying Error 400 Bad Request

Why can't I get a usable response from graphql with axios?

I'm successfully authenticating with the server, sending my graphql request and receiving a response. However the response isn't quite right.
This is just a simple nodejs, axios, graphql situation. I can get a correct respose via postman or curl but not with node. I've tried fetch as well to no avail. Am I doing something wrong? This is for the producthunt api, the api explorer is located at here
require('dotenv').config()
const axios = require("axios");
const PH_KEY = process.env.PH_KEY;
const PH_SECRET = process.env.PH_SECRET;
const BASE_URL = process.env.BASE_URL;
const AUTH_URL = process.env.AUTH_URL;
const GRAPHQL_URL = process.env.GRAPHQL_URL;
const PH = axios.create({
baseURL: BASE_URL,
responseType: 'json',
headers: {
// 'Accept': 'application/json, text/plain, gzip, deflate, */*',
'Content-Type': 'application/json'
},
})
let TOKEN = 'Bearer '
const getAuth = async () => {
return await PH({
url: AUTH_URL,
method: "post",
data: {
client_id: `${PH_KEY}`,
client_secret: `${PH_SECRET}`,
grant_type: "client_credentials"
}
})
.then((res) => {
console.log('auth status ', res.status)
return res.data.access_token
})
.then((res) => {
TOKEN += res
console.log(TOKEN)
})
.catch((err) => {
console.log(err)
})
}
const getHunt = async () => {
await getAuth()
PH.defaults.headers.common['Authorization'] = TOKEN
return await PH({
url: GRAPHQL_URL,
method: 'post',
data:
{
query: `
query posts {
posts(order: RANKING, first: 1) {
edges {
node {
name
votesCount
user {
name
}
createdAt
}
}
}
}
`
}
})
.then((res) => {return res})
.then((res) => {
console.log(res.data)
return res.data
})
.catch((err) => {
console.log(err)
})
}
const Main = async () => {
await getHunt()
}
Main()
This is the output I receive in node:
[Running] node "/Users/fireinjun/Work/YAC/yac-ph-tophuntfunction/app.js"
auth status 200
Bearer #################################################
{ data: { posts: { edges: [Array] } } }
Here's what I'm expecting:
{
"data": {
"posts": {
"edges": [
{
"node": {
"name": "Trends by The Hustle",
"votesCount": 125,
"user": {
"name": "Jack Smith"
},
"createdAt": "2019-06-04T07:01:00Z"
}
}
]
}
}
}
I was accessing the data incorrectly! Apparently I needed to see the res.data.data.posts.edges[0]

Resources