Github GraphQL API for popular discussions - graphql

I need to find top 5 popular discussions in the last month for a Github repo. By popular, I mean most interacted with. I am using the below java-script code which gives me the total count of comments and reactions for each discussion. But how do I modify it get the total count of comments and reactions in the last month? I am new to GraphQL, so if someone has a better idea to achieve this, please help.
function get_repo_discussions(repo) {
var after = "";
var res = [];
do {
var query = ` \
query { \
repository(owner: ` + '"' + owner + '", name: "' + repo + `") { \
discussions(first:100 \
` + after + `\
) { \
totalCount \
pageInfo { \
startCursor \
endCursor \
hasNextPage \
hasPreviousPage \
} \
edges { \
node { \
number, title, url, createdAt \
comments {
totalCount \
}, \
reactions {
totalCount \
} \
} \
} \
} \
} \
} \
`;
var ql = 'https://api.github.com/graphql';
var response = UrlFetchApp.fetch(ql, {
method: "POST",
contentType: 'application/json',
headers: { Authorization: 'Bearer ' + token},
payload: JSON.stringify({query: query})
});
var json = response.getContentText();
data = JSON.parse(json);
// Logger.log(data.data.repository.discussions.pageInfo.hasNextPage);
var discussion_count = data.data.repository.discussions.edges.length;
var edges = data.data.repository.discussions.edges;
for (var i = 0; i < discussion_count;i++){
var node = edges[i].node;
var number = node.number;
var title = node.title;
var url = node.url;
var created_at = new Date(node.createdAt);
var comments = node.comments.totalCount;
var reactions = node.reactions.totalCount;
res.push([number,title, url, created_at,comments + reactions]);
}
if(data.data.repository.discussions.pageInfo.hasNextPage){
after = " after:" + '"' + data.data.repository.discussions.pageInfo.hasNextPage.endCursor + '"';
}
}
while(data.data.repository.discussions.pageInfo.hasNextPage ==true);
return res;
}

Related

Update text inside text file?

I can't find in create and update methods of Google Drive API, where should I put actual text that I want to be inside my text file. Where is this parameter?
With this query I only create empty file:
await window.gapi.client.drive.files.create({
resource: {
'name': `${knowledgeFile.id}.txt`,
'parents': [`${srcDataFolderId}`]
},
media: {
mimeType: 'text/plain',
body: convertHTMLToPlainText(knowledgeFileHTML)
},
fields: 'id'
})
After creating a text file on your drive, you can update its content with the Files: update request
To do so
Specify the new content as a string
Transform the content string into a byte array
Get the existing file by its id
Read the file as binary string with FileReader
Create a new file metadara as a bytearray merging the old and the new contents
Perform an Files:Update request specifying the new file metadata as request body
Sample
function updateFile() {
var fileId = "YOUR FILE ID";
var contentString = "Hello world";
var contentArray = new Array(contentString.length);
for (var i = 0; i < contentArray.length; i++) {
contentArray[i] = contentString.charCodeAt(i);
}
var byteArray = new Uint8Array(contentArray);
var newData = new Blob([byteArray], {
type: 'text/plain'
});
var request = gapi.client.drive.files.get({
'fileId': fileId
});
request.execute(function(oldData) {
var boundary = '-------314159265358979323846';
var delimiter = "\r\n--" + boundary + "\r\n";
var close_delim = "\r\n--" + boundary + "--";
var reader = new FileReader();
reader.readAsBinaryString(newData);
reader.onload = function(e) {
var contentType = newData.type || 'application/octet-stream';
var base64Data = btoa(reader.result);
var multipartRequestBody =
delimiter + 'Content-Type: application/json\r\n\r\n' + JSON.stringify(oldData) + delimiter + 'Content-Type: ' + contentType + '\r\n' + 'Content-Transfer-Encoding: base64\r\n' + '\r\n' + base64Data + close_delim;
var request = gapi.client.request({
'path': '/upload/drive/v2/files/' + fileId,
'method': 'PUT',
'params': {
'uploadType': 'multipart',
'alt': 'json'
},
'headers': {
'Content-Type': 'multipart/mixed; boundary="' + boundary + '"'
},
'body': multipartRequestBody
});
request.execute();
}
});
}

How to Use Take and Skip Function in MVC

I want to Load Data and skip previous data which already append in the view using skip and take count in mvc.Here is my View where i am getting data
var skipCount = 5;
var takeCount = 5;
function loadMore() {
$(window).bind('scroll', bindScroll);
itemCount = takeCount;
skipCount += takeCount;
setTimeout(function () {
getFeed();
},100);
}
function bindScroll() {
if ($(window).scrollLeft() + $(window).width() > $('.tile-area').width() - 130) {
$(window).unbind('scroll');
loadMore();
}
}
function getFeed() {
$.ajax({
type: "Post",
url: "/PlanetFeed/PlanetfeedPartial",
dataType: "html",
data: { id: planetFeedOwnerId, filterType: filterType, taggedItemGraphId: taggedItemGraphId, itemCount: takeCount, SkipCount: skipCount }, //"feedGraphId=10696",
success: function (data) {
if (data === null) {
} else {
$('.tile-area-title').html("");
var div = $('.planetFeed:last');
div.after(data);
skipCount += takeCount + 1;
}
});
}
And Here is My Controller Where I am Passing Parameter
public ActionResult PlanetfeedPartial(Guid id, string filterType, Guid taggedItemGraphId, int itemCount, int SkipCount)
{
var planetfeedsOrder = from p in db.PlanetFeeds
where p.CurrentState != 1
join s in searchTag on p.PlanetFeedGraphId equals s.SecondaryTaggedGraphItemId
join g in db.Graphs on p.PlanetFeedItemGraphId equals g.GraphID
join u in db.UserInfos on p.PlanetFeedPosterId equals u.UserInfoID
orderby p.PostDate descending
select new PlanetFeedViewModel
{
Username = u.FirstName + " " + u.LastName,
isRootFeed = p.isRootFeed,
PostDate = p.PostDate,
CommentCount = g.CountResponses,
CountPositiveReactions = g.CountPositiveReactions,
CountNegativeReactions = g.CountNegativeReactions,
ItemID = g.ItemID,
UserLevel = u.UserLevel,
CurrentState = p.CurrentState,
Address = g.Address
};
return PartialView("_PlanetfeedPartial", planetfeedsOrder.OrderByDescending(p => p.PostDate).Skip(SkipCount).Take(itemCount).ToList());
}
I am not getting proper Data and every time when i am loading data in scroll getting different data not in a proper sequence and all data not loading
var planetfeedsOrder = (from p in db.PlanetFeeds
where p.CurrentState != 1
join s in searchTag on p.PlanetFeedGraphId equals s.SecondaryTaggedGraphItemId
join g in db.Graphs on p.PlanetFeedItemGraphId equals g.GraphID
join u in db.UserInfos on p.PlanetFeedPosterId equals u.UserInfoID
orderby p.PostDate descending
select new PlanetFeedViewModel
{
Username = u.FirstName + " " + u.LastName,
isRootFeed = p.isRootFeed,
PostDate = p.PostDate,
CommentCount = g.CountResponses,
CountPositiveReactions = g.CountPositiveReactions,
CountNegativeReactions = g.CountNegativeReactions,
ItemID = g.ItemID,
UserLevel = u.UserLevel,
CurrentState = p.CurrentState,
Address = g.Address
}).orderby(o=>o.id).skip(100);
skip One hundred then shows your data and create order by any id or string that you want sequence data.

Json result returned as a file in Internet Explorer?

net MVC application, in which I have multiple charts. On these charts, I have applied filters and by clicking each filter, I do an ajax call which returns the result in Json and then applies to the charts.
Now its working perfectly in Firefox and Chrome, but in Internet Explorer - Ajax call is always unsuccessful. I tried hitting the web api url directly through my browser and the issue it seems is, the result json was being returned as a file to be downloaded.
This is my ajax code :
function getIssueResolvedGraphdata(control, departCode, departName) {
$.ajax(
{
type: "GET",
url: WebApiURL + "/api/home/GetQueryIssueResolvedData?deptCode=" + departCode,
dataType: "json",
crossDomain: true,
async: true,
cache: false,
success: function (myData) {
var resolvedStartDate = myData.data.IssueResolvedStartDate;
var issueData = myData.data.IssueData;
var resolveData = myData.data.ResolvedData;
//converting issueData into integer array...
var issue = issueData.replace("[", "");
var issue1 = issue.replace("]", "");
var issue2 = issue1.split(",");
for (var i = 0; i < issue2.length; i++) { issue2[i] = parseInt(issue2[i]); }
//converting resolvedData into integer array
var resolve = resolveData.replace("[", "");
var resolve1 = resolve.replace("]", "");
var resolve2 = resolve1.split(",");
for (var j = 0; j < resolve2.length; j++) { resolve2[j] = parseInt(resolve2[j]); }
//getting max value from array...
var issueMaxVal = Math.max.apply(null, issue2);
var resolveMaxVal = Math.max.apply(null, resolve2);
//Eliminating leading zeros in issue array
var removeIndex = 0;
var myDate;
var newDate;
var arrayLength;
if (issueMaxVal != 0) {
arrayLength = issue2.length;
for (var i = 0; i < arrayLength; i++) {
if (issue2[0] == 0) {
issue2.splice(0, 1);
removeIndex = i;
} else {
break;
}
}
//Getting days count of current month
var monthStart = new Date(new Date().getFullYear(), new Date().getMonth(), 1);
var monthEnd = new Date(new Date().getFullYear(), new Date().getMonth() + 1, 1);
var monthLength = (monthEnd - monthStart) / (1000 * 60 * 60 * 24);
var monthDays = 0;
if (monthLength == 28) {
monthDays = removeIndex;
}
else if (monthLength == 30) {
monthDays = removeIndex + 1;
}
else if (monthLength == 31 || monthLength == 29) {
monthDays = removeIndex + 2;
}
//matching the resultant issue array with resolve array & setting start date
var iDate = resolvedStartDate;
var tDate = '';
for (var i = 0; i < iDate.length; i++) {
if (iDate[i] == ',') {
tDate += '/';
}
else {
tDate += iDate[i];
}
}
if (removeIndex != 0) {
resolve2.splice(0, (removeIndex + 1));
var myDate = new Date(tDate);
myDate.setDate(myDate.getDate() + monthDays);
newDate = Date.UTC(myDate.getFullYear(), (myDate.getMonth() + 1), myDate.getDate());
} else {
var myDate = new Date(tDate);
newDate = Date.UTC(myDate.getFullYear(), (myDate.getMonth() + 1), myDate.getDate());
}
} else {
alert("Empty");
}
//updating chart here...
var chart = $('#performance-cart').highcharts();
chart.series[0].update({
pointStart: newDate,
data: issue2
});
chart.series[1].update({
pointStart: newDate,
data: resolve2
});
if (issueMaxVal > resolveMaxVal) {
chart.yAxis[0].setExtremes(0, issueMaxVal);
} else {
chart.yAxis[0].setExtremes(0, resolveMaxVal);
}
},
error: function (x, e) {
alert('There seems to be some problem while fetching records!');
} });}
Code from web api controller :
[HttpGet]
[CrossDomainActionFilter]
public Response<GraphIssueResolvedWrapper> GetQueryIssueResolvedData(string deptCode)
{
Response<GraphIssueResolvedWrapper> objResponse = new Response<GraphIssueResolvedWrapper>();
GraphIssueResolvedWrapper objGraphIssueResolvedWrapper = new GraphIssueResolvedWrapper();
try
{
....code.....
objResponse.isSuccess = true;
objResponse.errorDetail = string.Empty;
objResponse.data = objGraphIssueResolvedWrapper;
}
catch (Exception ex)
{
objResponse.isSuccess = false;
objResponse.errorDetail = ex.Message.ToString();
objResponse.data = null;
}
return objResponse;
}
Reponse Class :
public class Response<T>
{
public bool isSuccess { get; set; }
public string errorDetail { get; set; }
public T data { get; set; }
}
I am stuck at this for hours now. Any help will be appreciated.
I have solved my problem by using the following code : ( I guess it needed CORS support)
function isIE() {
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE");
if (msie > 0)
return true;
return false;
}
Then in document.ready function of my binding script :
$(document).ready(function () {
if (isIE())
$.support.cors = true;
});
Note : it still download Json stream as a file but now my AJAX call is successful upon each hit.
You've missed contentType: 'text/html' which is pretty important for IE7-8:
$.ajax(
{
type: "GET",
url: WebApiURL + "/api/home/GetQueryIssueResolvedData?deptCode=" + departCode,
dataType: "json",
contentType: 'text/html'
crossDomain: true,
async: true,
cache: false,
success: function (myData) {
var result = JSON.parse(myData);
///...code...
},
error: function (x, e) {
alert('There seems to be some problem while fetching records!');
}
}
);
To make it works in IE7-8 you also need to be sure that you've writing Conrent-Type Header into your response on server side. Add this line right before return statement;
response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html; charset=iso-8859-1");
And in code probably you will need to parse result in success method by using JSON.parse(myData);

docpad plugins server.extend argument options not containing any express middleware with last version of docpad

I faced problems using minicms docpad plugin with last version of docpad. This plugin implements server.extend function which is being passed an opts object containing the express module used by docpad (during its plugin initialisation process). Minicms plugin is making use of a bunch of expressJS middleware :
express.static()
express.cookieParser()
express.cookieSession()
Unfortunately none of those middleware functions are available in the opts.express object and i'm wondering if there's been some changes in the recent docpad versions. Is there any workaround or docpad configuration i should be aware of ?
minicms.plugin.js code
// Generated by IcedCoffeeScript 1.3.3g
(function() {
var YAML, applyContext, cc, deepCopy, exec, fs, gm, sessionBridge, shellEscape, slugify, uuid,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
slugify = require('./utils/slugify');
cc = require('coffeecup');
uuid = require('node-uuid');
gm = require('gm');
fs = require('fs');
exec = require('child_process').exec;
shellEscape = require('./utils/shellEscape');
deepCopy = require('owl-deepcopy').deepCopy;
YAML = require('yamljs');
applyContext = require('./utils/applyContext');
sessionBridge = require('./utils/sessionBridge');
module.exports = function(BasePlugin) {
var MinicmsPlugin;
return MinicmsPlugin = (function(_super) {
__extends(MinicmsPlugin, _super);
function MinicmsPlugin() {
return MinicmsPlugin.__super__.constructor.apply(this, arguments);
}
MinicmsPlugin.prototype.name = 'minicms';
MinicmsPlugin.prototype.config = {
prefix: {
url: 'cms',
meta: 'cms'
},
validate: require('./utils/validate'),
sanitize: require('./utils/sanitize')
};
MinicmsPlugin.prototype.docpadReady = function(opts) {
return this.docpad.action('watch', {}, function(err) {
var _ref;
if (err) {
process.stderr.write(("" + ((_ref = err.message) != null ? _ref : err)).trim() + "\n");
}
return this.docpad.log("Force watching file for minicms.");
});
};
MinicmsPlugin.prototype.serverExtend = function(opts) {
var app, config, docpad, express;
app = opts.server;
express = opts.express; // express module
console.log(opts.express._router.middleware);
docpad = this.docpad;
config = this.config;
exec("rm -rf " + (shellEscape(docpad.config.srcPath + '/files/tmp')), function() {});
app.use('/' + this.config.prefix.url, express["static"](__dirname + '/static')); // express.static middleware
if (!(this.config.secret != null)) {
throw "Secret is required for cookie sessions (minicms)";
}
app.use(express.cookieParser()); // express.cookieParser middleware
app.use(express.cookieSession({ // express.cookieSession middleware
secret: this.config.secret
}));
app.get('/' + this.config.prefix.url + '/logout', require('./routes/logout').bind(this));
app.get('/' + this.config.prefix.url + '/login', require('./routes/login').bind(this));
app.post('/' + this.config.prefix.url + '/login', require('./routes/loginSubmit').bind(this));
app.get('/' + this.config.prefix.url, require('./routes/root').bind(this));
app.get('/' + this.config.prefix.url + '/:content/list', require('./routes/list').bind(this));
app.get('/' + this.config.prefix.url + '/:content/edit', require('./routes/edit').bind(this));
app.post('/' + this.config.prefix.url + '/:content/edit', require('./routes/edit').bind(this));
app.post('/' + this.config.prefix.url + '/generate', require('./routes/generate').bind(this));
console.log('/' + this.config.prefix.url + '/:content/:field/upload');
app.post('/' + this.config.prefix.url + '/:content/:field/upload', require('./routes/upload').bind(this));
};
return MinicmsPlugin;
})(BasePlugin);
};
}).call(this);

AJAX POST request on IE fails with error "No Transport"?

I'm trying to make an AJAX request to a public service
Here's the code:
$.ajax({
url : "http://api.geonames.org/citiesJSON",
type : 'POST',
cache : false,
dataType : 'json',
data : {
username: "demo",
north:10,
south: 10,
east:10,
west:10}
}).done(function(data) {
alert("Success: " + JSON.stringify(data));
}).fail(function(a, b, c, d) {
alert("Failure: "
+ JSON.stringify(a) + " "
+ JSON.stringify(b) + " "
+ JSON.stringify(c) + " "
+ JSON.stringify(d) );
});
You may try it in this link: http://jsfiddle.net/hDXq3/
The response is retrieved successfully on Chrome & Firefox, and the output is as follows:
But for IE, the fails alerting:
Failure: {"readyState":0,"status":0,"statusText":"No Transport"} "error" "No Transport" undefined
Why it's not working on IE ? and how to fix this ?
Here's the solution for those who are interested:
if (!jQuery.support.cors && window.XDomainRequest) {
var httpRegEx = /^https?:\/\//i;
var getOrPostRegEx = /^get|post$/i;
var sameSchemeRegEx = new RegExp('^'+location.protocol, 'i');
var xmlRegEx = /\/xml/i;
// ajaxTransport exists in jQuery 1.5+
jQuery.ajaxTransport('text html xml json', function(options, userOptions, jqXHR){
// XDomainRequests must be: asynchronous, GET or POST methods, HTTP or HTTPS protocol, and same scheme as calling page
if (options.crossDomain && options.async && getOrPostRegEx.test(options.type) && httpRegEx.test(userOptions.url) && sameSchemeRegEx.test(userOptions.url)) {
var xdr = null;
var userType = (userOptions.dataType||'').toLowerCase();
return {
send: function(headers, complete){
xdr = new XDomainRequest();
if (/^\d+$/.test(userOptions.timeout)) {
xdr.timeout = userOptions.timeout;
}
xdr.ontimeout = function(){
complete(500, 'timeout');
};
xdr.onload = function(){
var allResponseHeaders = 'Content-Length: ' + xdr.responseText.length + '\r\nContent-Type: ' + xdr.contentType;
var status = {
code: 200,
message: 'success'
};
var responses = {
text: xdr.responseText
};
try {
if (userType === 'json') {
try {
responses.json = JSON.parse(xdr.responseText);
} catch(e) {
status.code = 500;
status.message = 'parseerror';
//throw 'Invalid JSON: ' + xdr.responseText;
}
} else if ((userType === 'xml') || ((userType !== 'text') && xmlRegEx.test(xdr.contentType))) {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.async = false;
try {
doc.loadXML(xdr.responseText);
} catch(e) {
doc = undefined;
}
if (!doc || !doc.documentElement || doc.getElementsByTagName('parsererror').length) {
status.code = 500;
status.message = 'parseerror';
throw 'Invalid XML: ' + xdr.responseText;
}
responses.xml = doc;
}
} catch(parseMessage) {
throw parseMessage;
} finally {
complete(status.code, status.message, responses, allResponseHeaders);
}
};
xdr.onerror = function(){
complete(500, 'error', {
text: xdr.responseText
});
};
xdr.open(options.type, options.url);
//xdr.send(userOptions.data);
xdr.send();
},
abort: function(){
if (xdr) {
xdr.abort();
}
}
};
}
});
};
jQuery.support.cors = true;
$.ajax({
url : "http://api.geonames.org/citiesJSON",
crossDomain: true,
type : 'POST',
cache : false,
dataType : 'json',
data : {
username: "demo",
north:10,
south: 10,
east:10,
west:10}
}).done(function(data) {
alert("Success: " + JSON.stringify(data));
}).fail(function(a, b, c, d) {
alert("Failure: "
+ JSON.stringify(a) + " "
+ JSON.stringify(b) + " "
+ JSON.stringify(c) + " "
+ JSON.stringify(d) );
});
You may try it in this link: http://jsfiddle.net/bjW8t/4/
Just include the jQuery ajaxTransport extension that uses XDomainRequest for IE8+.

Resources