await not efficient in asynchronous function - javascript

I am trying to parse pdf datas asynchronously, then populate a JS object with the content of the pdf file, and then return it in a Promise.
I am using the "pdfreader" module and its method parseFileItems()
async function parsePdfDatas(filePath){
var output = {};
var reader = new pdfreader.PdfReader();
await reader.parseFileItems(filePath, function(err, item) {
// item treatment populating output Object
});
return output;
}
parsePdfDatas("./****.pdf").then( function(output) {
console.log(output);
});
The await statement doesn't work, anybody get an idea ?
EDIT
After xMayank answer, i tried as follows, which doesn't work neither:
const fs = require('fs');
var pdfreader = require("pdfreader");
var row = {
id: "",
muban: "",
get mID() {
this.id.slice(6,8);
},
tambon: "",
get tID() {
this.id.slice(4,6);
},
amphoe: "",
get aID() {
this.id.slice(2,4);
},
changwat: "",
get cID() {
this.id.slice(0,2);
}
}
function parsePdfDatas(filePath){
return new Promise(function(resolve, reject){
var output = {};
var reader = new pdfreader.PdfReader();
reader.parseFileItems(filePath, function(err, item) {
if(item && item.text && item.text.match(/^-{1,3}[0-9]{1,4}-{1,3}$/) === null && item.y != 2.887){
if(item.x === 2.388){
// If the row object contains a muban entry, we push it at the end of output
if(row.id !== ""){
//console.log(row);
output[row.id] = {mName : row.muban, tName : row.tambon, aName : row.amphoe, cName : row.changwat};
}
// new line, row object reinitialization
row.id = row.muban = row.tambon = row.amphoe = row.changwat = "";
}
// correction for ่ ้
if(item.R[0].T === "%E0%B8%BD") item.text = "่";
if(item.R[0].T === "%E0%B8%BE") item.text = "้";
if(item.x >= 2.388 && item.x < 11.303)
row.id += item.text;
else if(item.x >= 11.303 && item.x < 17.969)
row.muban += item.text;
else if(item.x >= 17.969 && item.x < 23.782)
row.tambon += item.text;
else if(item.x >= 23.782 && item.x < 29.698)
row.amphoe += item.text;
else if(item.x >= 29.698)
row.changwat += item.text;
console.log(item.R[0].T + " -> " + item.text);
//console.log(item.text + " : x = " + item.x + " | y = " + item.y);
}
});
resolve(output);
});
}
parsePdfDatas("./files/mubans0.pdf").then((output) => {
console.log(output);
});

Works fine.
const { PdfReader } = require("pdfreader");
function readFile(file){
return new Promise(function(resolve, reject){
new PdfReader().parseFileItems(file, function(err, item) {
if (err) reject(err);
else if (!item) resolve();
else if (item.text) resolve(item.text);
});
})
}
readFile("./****.pdf")
.then(result =>{
console.log("Here", result)
})

Related

Assigning a viewbag to a variable in a JQuery function

I'm using MVC and am trying to check if the item has enough stock in inventory. I do this in my controller by
[HttpPost]
[ValidateAntiForgeryToken]
[Audit]
public void AddUnits(int so_id, int site_id, int[] addItem_id, int[] addItem_qty)
{
// Loop however many times is necessary to iterate through the largest array
for (int i = 0; i < Math.Max(Math.Max(addItem_id.Length, addComp_id.Length), addPart_id.Length); i++)
{
foreach (SODetails sod in db.SalesOrders.Find(so_id).SalesDetails)
{
if (i < addItem_id.Length && addItem_qty[i] != 0 && sod.ItemID == addItem_id[i] && addItem_id[i] != 365 && addItem_id[i] != 410)
{
sod.item_qty += addItem_qty[i];
sod.item_discount = addItem_disc[i];
addItem_id[i] = 0;
addItem_qty[i] = 0;
addItem_disc[i] = 0;
}
}
db.SaveChanges();
if(i < addItem_qty.Length && addItem_qty[i] != 0)
{
SODetails sODetails = new SODetails
{
SalesOrderID = so_id,
SiteID = site_id
};
// Only add a unit to the SODetails object if it's not null and has an id and quanitity specified
if(i < addItem_id.Length && addItem_id[i] != 0 && addItem_qty[i] != 0)
{
sODetails.ItemID = addItem_id[i];
sODetails.item_qty = addItem_qty[i];
sODetails.item_discount = addItem_disc[i];
}
SalesOrder SO = db.SalesOrders.Find(sODetails.SalesOrderID);
SODetails salesOrderDetails = db.SODetails.Add(sODetails);
salesOrderDetails.SalesOrder = SO;
Item SO_Item = db.Items.Find(sODetails.ItemID);
if (SO_Item != null)
{
ViewBag.itemOnHand = SO_Item.On_Hand;
sODetails.item_qty = sODetails.item_qty == null ? 0 : sODetails.item_qty;
int qtyOrdered = sODetails.item_qty == null ? 0 : (int)sODetails.item_qty;
salesOrderDetails.dynamicItem_qty = qtyOrdered;
if (SO_Item.SalesOrderMessage != null)
TempData["SalesOrderMessage"] = SO_Item.SalesOrderMessage;
}
}
}
}
db.SaveChanges();
}
Currently I'm trying to pass the inventory count of that item into the viewbag by doing
ViewBag.itemOnHand = SO_Item.On_Hand;
Then my view Jquery function looks like this
// Get all item ids and quantities and store them in arrays
var itemssel = document.getElementsByClassName("Item-select");
var itemsqtysel = document.getElementsByClassName("Item-qty");
var itemsdiscsel = document.getElementsByClassName("Item-disc");
var itemOnHand = #ViewBag.itemOnHand;
for (i = 0; i < itemssel.length; i++) {
items[i] = itemssel[i].options[itemssel[i].selectedIndex].value;
itemsqty[i] = itemsqtysel[i].value;
itemsdisc[i] = itemsdiscsel[i].value;
if (itemsqty[i] < 0) {
alert("Quantities can't be negative!");
return;
}
if (itemsqty[i] < itemOnHand) {
alert("Not enough inventory in site!");
return;
}
// The add units method is then called here
// Send all the values to the AJAX function and respond with success or error
$.ajax({
type: "POST",
url: "#IGT.baseUrl/SODetailsAjax/AddUnits",
traditional: true,
data: {
__RequestVerificationToken: token,
so_id: #Int32.Parse(Request["orderId"]),
site_id: site,
addItem_id: items,
addItem_qty: itemsqty,
addItem_disc: itemsdisc,
addComp_id: comps,
addComp_qty: compsqty,
addComp_disc: compsdisc,
addPart_id: parts,
addPart_qty: partsqty,
addPart_disc: partsdisc
},
success: function () {
location.href = "../SalesOrders/Details?id=#so.ID";
},
error: function (jqXHR, status, error) {
alert("Error: " + error);
}
});
But it doesn't work correctly as it is right now. Why is this?
As requested, here is my GET method for the page before it posts
// GET: SODetails/Create
[RestrictAccess(restriction = AccessRestrictions.ModifySalesOrder)]
public ActionResult Create(int orderId)
{
var SOID = (from i in db.SalesOrders.Where(x => x.ID == orderId).Where(x => x.deleted == false)
select new
{
SO_id = i.ID,
status = i.ID + " (Status: " + i.SalesOrderStatus +")",
}).OrderByDescending(x => x.SO_id).ToList();
var item = (from i in db.Items.Where(x => x.deleted == false)
select new
{
itemID = i.ID,
itemName = i.Product_Number + " : " + i.ItemID + " : " + i.Name
}).OrderBy(x => x.itemName).ToList();
var component = (from c in db.Components.Where(x => x.deleted == false)
select new
{
compID = c.ID,
compName = c.Product_Number + " : " + c.ComponentID + " : " + c.Name
}).OrderBy(x => x.compName).ToList();
var part = (from c in db.Parts.Where(x => x.deleted == false)
select new
{
partID = c.ID,
partName = c.Product_Number + " : " + c.PartID + " : " + c.Name
}).OrderBy(x => x.partName).ToList();
var sites = (from s in db.Sites
select new
{
siteID = s.ID,
siteName = s.Name
}).OrderBy(x => x.siteName).ToList();
sites.Insert(0, new { siteID = 0, siteName = "Main Inventory" });
var masters = db.Items.Where(x => x.Product_Number.Contains("106101") || x.ItemID.Contains("106101"));
List<int> ids = new List<int>();
foreach(Item i in masters.Where(x => x.Product_Number.Contains("BMU") || x.Product_Number.Contains("BMDU") || x.Product_Number.Contains("BMS")))
{
ids.Add(i.ID);
}
ViewBag.BMUMasters = ids.ToArray();
ids = new List<int>();
foreach (Item i in masters.Where(x => x.Product_Number.Contains("GMU")))
{
ids.Add(i.ID);
}
ViewBag.GMUMasters = ids.ToArray();
ViewBag.ItemID = new SelectList(item, "itemID", "itemName");
ViewBag.ComponentID = new SelectList(component, "compID", "compName");
ViewBag.PartID = new SelectList(part, "partID", "partName");
ViewBag.SalesOrderID = new SelectList(SOID, "SO_id", "status");
ViewBag.SiteID = new SelectList(sites, "siteID", "siteName");
ViewBag.invSiteID = new SelectList(sites, "siteID", "siteName");
return View();
}
Try to add null coalescing, this will return 0 if the ViewBag.itemOnHand is empty;
var itemOnHand = #(ViewBag.itemOnHand ?? 0);
Then if you're going to use it for some number operations try to force it to become an integer;
var itemOnHand = Number(#(ViewBag.itemOnHand ?? 0));
Since you already have an if statement or null checks prior to ViewBag assignment, you could simply return the view and add a ViewBag.Error;
if (SO_Item != null)
{
// .. if not null
}else{
// if null return view
ViewBag.Error = "your error here";
return View();
}
Then somewhere in your view add this;
#if(ViewBag.Error != null){
<div class="row error">
<div class="col-md-12">
Error occured: <strong>#ViewBag.Error</strong>
</div>
</div>
}

Convert array to pipe separated

How to convert array EX-["lat","long","abc","def","abcc","deef",]
into [lat,long | abc,def | abcc,deef] in javascript.
I am facing issue with distance matrix Api...
Below is my code
export async function getStoreDistance(locationDetails) {
destinationRequest = [];
let destinationRequest = locationDetails.destinations.map(location => {
console.log('destreqlocation', location);
return `${location.lat},${location.long} `;
});
return await axios
.get(
`https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial
&origins=${locationDetails.origins.map(function(locationDetail) {
return locationDetail;
})}
&destinations=${destinationRequest}&key=**********`,
)
.then(function(response) {
// handle success
// return response;
})
.catch(function(error) {
// handle error
return error;
});
}
My solution to the problem.
const so1 = ["lat","long","abc","def","abcc","deef"]
let result = so1
.map((item, id, array) => ((id % 2) !== 0 && id !== (array.length - 1)) ? item + '|' : (id !== (array.length - 1)) ? item + '&' : item)
.join('')
.replace(/&/g, ',')
console.log( result )
console.log( `[${result}]` )
Try something like below
input = ["lat", "long", "abc", "def", "abcc", "deef"];
const [lat, long, ...rest] = input;
res = rest.reduce((acc, val, index) => {
if(index % 2 === 0) acc.push([]);
acc[acc.length -1].push(val);
return acc;
}, []);
resFinal = [[lat, long], ...res];
console.log(resFinal);
resFinalStr = resFinal.reduce((acc, val, index)=> {
if(index !== resFinal.length -1){
acc+=(val.join(",")) + "|";
}else{
acc += val.join(",")
}
return acc;
}, "")
console.log(resFinalStr)
console.log(`[${resFinalStr}]`)
An old-fashioned for loop should do the job fine:
function getStoreDistance(locationDetails) {
destinationRequest = locationDetails[0] || "";
for (let i = 1; i < locationDetails.length; i++) {
destinationRequest += (i % 2 ? "," : " | ") + locationDetails[i];
}
return destinationRequest;
}
// Demo
let response = ["lat","long","abc","def","abcc","deef"];
console.log(getStoreDistance(response));

Recursive java script function - out of control

The code below works. The code calls an API to get historical trades (100 trades each time pér pull). Because there is an limit - how many and how often im allowed to call the API - the structure is like recursive.
The flow is like this:
Get the current MAX tradeId - which is stored in the DB.
Now make a new PULL with startIndex = MaxId and a length of 100 (to pull 100 new trades).
FIRST when the callback function is called the main code continues and 100 new trades are pulled... ect. ect.
So...
The code SHOULD behave like - Psydo-code
var maxId = GetMaxIdFromDB();
Pull(maxId, 100, callback);
function callback(){
... do different stuff..
maxId += 100;
Pull(maxId, 100, callback);
}
The strange thing and my question is: How can the API function "getProductTrades " be called more than one time - where my cursor variable contains the SAME value - when it is incremented with 100 (or the number of valid data elements each time).
I'm talking/ref. especially to the following lines:
wl.debug("getProductTrades - cursor: " + cursor + " Limit: " + limit);
publicClient.getProductTrades({'after': cursor, 'limit': limit}, callback);
The insertQuery.InsertMatchMsgArrayToDB(allData); method calls another DB method which returns a promise.
You can see a screenshot of the issue here:
http://screencast.com/t/DH8rz3UxnyZ
The real code is here:
pullTradesBetween: function (minTradeId, maxTradeId) {
var wl = new WinLog();
var tradeCounter = 0;
try {
var WebSocketEmit = new WSemitter();
var startTime = new Date().toLocaleString();
var executeTradePullAgain = null;
wl.debug("REST API START: " + startTime);
var cursor;
var incrementedCursorWith = 0;
if ((maxTradeId - minTradeId) < 100) {
cursor = maxTradeId + 1;
}
else
cursor = minTradeId + 100;
var callback = function (err, response, data) {
if (executeTradePullAgain !== null)
clearTimeout(executeTradePullAgain);
if (err)
wl.info("Err: " + err);
var validData = [];
incrementedCursorWith = 0;
if (response == null)
wl.info("RESPONSE ER NULL");
if (data !== null) {
for (var i = data.length - 1; i >= 0; i--) {
var obj = data[i];
var tradeId = parseInt(obj.trade_id);
if (obj !== null && (minTradeId <= tradeId && tradeId <= maxTradeId)) {
validData.push(data[i]);
}
}
if (validData.length == 0) {
wl.debug("Contains 0 elements!");
}
else {
cursor = cursor + validData.length;
incrementedCursorWith = validData.length;
insertDataToDB(validData);
}
}
else
wl.debug("DATA IS NULL!");
wl.debug("cursor: " + cursor + " maxTradeId: " + maxTradeId);
var diffToMax = maxTradeId - (cursor - incrementedCursorWith);
if (diffToMax >= 100)
pullTrades(cursor, 100); // 100 is default
else if (diffToMax >= 0)
pullTrades(maxTradeId + 1, diffToMax + 1); // X = Only the last trades in the given series of trades
else {
wl.info("REST API START: " + startTime + " REST API DONE: " + new Date().toLocaleString());
WebSocketEmit.syncHistoricalDataDone();
}
};
function pullTrades(cursor, limit) {
tradeCounter += limit;
if(tradeCounter % 10000 == 0){
wl.info('Downloaded: ' + tradeCounter + ' trades via REST API (Total: ' + cursor + ')');
}
pullTradesAgainIfServerDoesNotRespond(cursor, limit);
wl.debug("getProductTrades - cursor: " + cursor + " Limit: " + limit);
publicClient.getProductTrades({'after': cursor, 'limit': limit}, callback);
}
function pullTradesAgainIfServerDoesNotRespond(cursor, limit) {
executeTradePullAgain = setTimeout(function () {
wl.debug('pullTradesAgainIfServerDoesNotRespond called!');
pullTrades(cursor, limit);
}, 30000);
}
// SAVE DATA IN DB!
function insertDataToDB(allData) {
insertQuery.InsertMatchMsgArrayToDB(allData);
}
wl.debug("pull trades: " + cursor);
pullTrades(cursor, 100);
}
catch(err){
wl.info('pullTradesBetween: ' + err);
} }};
It happens when you get no data out of getProductionTrades.
If the data returned is null, you will never reach the lines
cursor = cursor + validData.length;
incrementedCursorWith = validData.length;
but you still call
pullTrades(cursor, 100);
at the end. I don't know if it's intended or an actual error so i leave the solution (should be trivial now) up to you.
I try to simplify your code
pullTradesBetween: function (minTradeId, maxTradeId) {
var WebSocketEmit = new WSemitter(); // try-catch ?
var curr = (maxTradeId - minTradeId < 100) ? maxTradeId + 1 : minTradeId + 100;
// function always return data or infinite error-loop
function getProductTrades (after, limit, callback) {
// try-catch ?
publicClient.getProductTrades ({after, limit}, function(err, data) {
if (err) {
console.log(err);
return getTrades(after, limit, callback);
}
callback(null, data);
});
}
function onDataReady (err, data) {
if (err)
throw new Error('Impossible!');
if (!data || !(data instanceof Array))
return ... smth on empty data ...
var validData = data.filter(function(obj) {
return obj &&
minTradeId <= parseInt(obj.trade_id) &&
parseInt(obj.trade_id) <= maxTradeId;
}).reverse();
if (validData.length == 0)
return ... smth on empty data ...
insertDataToDB(validData);
curr += validData.length; // maybe +-1
var remaining = maxTradeId - curr;
if (remainig == 0) {
console.log('Done');
// try-catch ?
WebSocketEmit.syncHistoricalDataDone();
}
return (remaining >= 100) ?
getProductTrades(curr, 100, onDataReady) :
getProductTrades(maxTradeId + 1, remaining + 1, onDataReady); // ??
}
getProductTrades(curr, 100, onDataReady);
}

Need help comparing the value inside array, with forEach loop

So basically I have some promise, forEach, just a lot of issues with this single problem I need to solve. So the variables I work with has below structure:
persons = [object, object, object]
where each object has { user:number , username: string, latitude:number, longitude:number}
from there I try to figure out if my user/username is inside of one of these objects, if not found id like it to be created, if found found id like it to update their location. Sounds simple, I think the problem has blown out of proportion but nothing works. The code I have now does not work, its either I can never figure out when the user is not there, or I can not figure out how to get to stop creating me every time it find a user who is not me.
var getswamp = function(item, index) {
return new Promise(function(resolve, reject){
var result = false;
if (item.user === user && item.username === username) {
if ((item.latitude !== latitudenew) || (item.longitude !== longitudenew)) {
var id = item.id;
swampdragon.update('locationcurrent', {
user: user,
latitude: latitudenew,
longititude: longitudenew,
username: username,
id: id
}, function (context, data) {
console.log("data updated", data);
result = true;
resolve(result);
}, function (context, data) {
console.log("You may not be updated");
});
} else {
console.log("No location change");
result = true;
}
}else{
if ( item.index === person.index){
console.log(person);
resolve(result)
}
}
});
};
person.forEach(function (item, index) {
var swamping = getswamp(item, index);
swamping.then(function (result) {
console.log(result);
if (result === true) {
console.log("We have you");
} else if (result === false && (index === person.length - 1)) {
console.log('Index: ' + index + ' Length of list is ' + person.length);
swampdragon.create('locationcurrent', {
user: user,
latitude: latitudenew,
longititude: longitudenew,
username: username
}, function (context, data) {
console.log("data created", data);
}, function (context, data) {
console.log("You may not be created")
});
}
})
});
Any help/ideas would just be great.
The Promise is used when some asynchronous event happened.
Since I can not create such event, I made a static code as below:
var persons = new Array();
persons.indexOf = function(person) {
var index = -1;
this.forEach(function(obj, i) {
if (person.username == obj.username) {
index = i;
}
});
return index;
}
persons.addOrUpdate = function(person) {
var index = this.indexOf(person);
if (index == -1) {
person.user = this.length + 1;
this.push(person);
}
else { // update case
var obj = this[index];
obj.latitude = person.latitude;
obj.longitude = person.longitude;
}
}
persons.print = function() {
var str = "";
this.forEach(function(obj) {
str += obj.user + ". " + obj.username + " at location (" +
obj.latitude + ":" + obj.longitude + ")\n";
});
return str;
}
persons.addOrUpdate({username:'Adam', latitude:-0.0045, longitude:14.2015});
persons.addOrUpdate({username:'Eve', latitude:-0.0045, longitude:14.2015});
persons.addOrUpdate({username:'Abel', latitude:-0.0045, longitude:14.2015});
// Updating Able location
var person = {username:'Abel', latitude:10.1145, longitude:14.1234};
persons.addOrUpdate(person);
alert(persons.print());

Instagram instafeed Image rotator/Slider

This is my first post on StackOverflow and might I say, what a great and helpful resource this is. I have been able to find many answers to my questions and hope to do the same with this one. On to the issue at hand... I am currently using the instafeed.js (http://instafeedjs.com/) script to pull in images from instagram and display them on my site.
What I'm trying to accomplish is to have 9 items display, then if I hit the "next" button, it would replace the current 9 images and load the next 9 images and, if the "previous" button is clicked it would go back and show the previous 9 images.
Currently it only renders one image thumb that scrolls through 9 images then stops. Swapping only the one image at a time. A sample of the current working code with only 1 image displaying can be found here - http://codepen.io/stevenschobert/pen/iHxfw
Here is my JavaScript for the instafeed call:
var count = 1;
var feed;
feed = new Instafeed({
clientId: '68be8b63013048ff81bb4ac8b02b606e',
limit: 9,
resolution: 'standard_resolution',
template: '<img src="{{image}}" /><div class="likes">♥ {{likes}}</div>',
mock: true,
after: function () {
var images = $("#instafeed").find('a');
$.each(images, function(index, image) {
var delay = (index * 75) + 'ms';
$(image).css('-webkit-animation-delay', delay);
$(image).css('-moz-animation-delay', delay);
$(image).css('-ms-animation-delay', delay);
$(image).css('-o-animation-delay', delay);
$(image).css('animation-delay', delay);
$(image).addClass('animated fadeInUp pic-'+count++);
});
},
custom: {
images: [],
currentImage: 0,
showImage: function () {
var result, image;
image = this.options.custom.images[this.options.custom.currentImage];
result = this._makeTemplate(this.options.template, {
model: image,
id: image.id,
link: image.link,
image: image.images[this.options.resolution].url,
caption: this._getObjectProperty(image, 'caption.text'),
likes: image.likes.count,
comments: image.comments.count,
location: this._getObjectProperty(image, 'location.name')
});
$("#instafeed").html(result);
}
},
success: function (data) {
this.options.custom.images = data.data;
this.options.custom.showImage.call(this);
}
});
feed.run();
$(".next").click(function () {
var length, current;
current = feed.options.custom.currentImage;
length = feed.options.custom.images.length;
if (current < length - 1) {
feed.options.custom.currentImage++;
feed.options.custom.showImage.call(feed);
}
});
$(".prev").click(function () {
var length, current;
current = feed.options.custom.currentImage;
length = feed.options.custom.images.length;
if (current > 0) {
feed.options.custom.currentImage--
feed.options.custom.showImage.call(feed);
}
});
My HTML:
<div id="instafeed"></div>
<div class="controls">
<div class="prev"><- prev</div>
<div class="next">next -></div>
</div>
The Instafeed.js code:
(function() { var Instafeed, root; Instafeed = (function() {
function Instafeed(params) {
var option, value;
this.options = {
target: 'instafeed',
get: 'popular',
resolution: 'thumbnail',
sortBy: 'most-recent',
links: true,
limit: 15,
mock: false
};
if (typeof params === 'object') {
for (option in params) {
value = params[option];
this.options[option] = value;
}
}
this.unique = this._genKey();
}
Instafeed.prototype.run = function() {
var header, instanceName, script;
if (typeof this.options.clientId !== 'string') {
if (typeof this.options.accessToken !== 'string') {
throw new Error("Missing clientId or accessToken.");
}
}
if (typeof this.options.accessToken !== 'string') {
if (typeof this.options.clientId !== 'string') {
throw new Error("Missing clientId or accessToken.");
}
}
if ((this.options.before != null) && typeof this.options.before === 'function') {
this.options.before.call(this);
}
if (typeof document !== "undefined" && document !== null) {
script = document.createElement('script');
script.id = 'instafeed-fetcher';
script.src = this._buildUrl();
header = document.getElementsByTagName('head');
header[0].appendChild(script);
instanceName = "instafeedCache" + this.unique;
window[instanceName] = new Instafeed(this.options);
window[instanceName].unique = this.unique;
}
return true;
};
Instafeed.prototype.parse = function(response) {
var anchor, fragment, header, htmlString, image, imageString, images, img, instanceName, reverse, sortSettings, _i, _j, _len, _len1;
if (typeof response !== 'object') {
if ((this.options.error != null) && typeof this.options.error === 'function') {
this.options.error.call(this, 'Invalid JSON data');
return false;
} else {
throw new Error('Invalid JSON response');
}
}
if (response.meta.code !== 200) {
if ((this.options.error != null) && typeof this.options.error === 'function') {
this.options.error.call(this, response.meta.error_message);
return false;
} else {
throw new Error("Error from Instagram: " + response.meta.error_message);
}
}
if (response.data.length === 0) {
if ((this.options.error != null) && typeof this.options.error === 'function') {
this.options.error.call(this, 'No images were returned from Instagram');
return false;
} else {
throw new Error('No images were returned from Instagram');
}
}
if ((this.options.success != null) && typeof this.options.success === 'function') {
this.options.success.call(this, response);
}
if (this.options.sortBy !== 'most-recent') {
if (this.options.sortBy === 'random') {
sortSettings = ['', 'random'];
} else {
sortSettings = this.options.sortBy.split('-');
}
reverse = sortSettings[0] === 'least' ? true : false;
switch (sortSettings[1]) {
case 'random':
response.data.sort(function() {
return 0.5 - Math.random();
});
break;
case 'recent':
response.data = this._sortBy(response.data, 'created_time', reverse);
break;
case 'liked':
response.data = this._sortBy(response.data, 'likes.count', reverse);
break;
case 'commented':
response.data = this._sortBy(response.data, 'comments.count', reverse);
break;
default:
throw new Error("Invalid option for sortBy: '" + this.options.sortBy + "'.");
}
}
if ((typeof document !== "undefined" && document !== null) && this.options.mock === false) {
document.getElementById(this.options.target).innerHTML = '';
images = response.data;
if (images.length > this.options.limit) {
images = images.slice(0, this.options.limit + 1 || 9e9);
}
if ((this.options.template != null) && typeof this.options.template === 'string') {
htmlString = '';
imageString = '';
for (_i = 0, _len = images.length; _i < _len; _i++) {
image = images[_i];
imageString = this._makeTemplate(this.options.template, {
model: image,
id: image.id,
link: image.link,
image: image.images[this.options.resolution].url,
caption: this._getObjectProperty(image, 'caption.text'),
likes: image.likes.count,
comments: image.comments.count,
location: this._getObjectProperty(image, 'location.name')
});
htmlString += imageString;
}
document.getElementById(this.options.target).innerHTML = htmlString;
} else {
fragment = document.createDocumentFragment();
for (_j = 0, _len1 = images.length; _j < _len1; _j++) {
image = images[_j];
img = document.createElement('img');
img.src = image.images[this.options.resolution].url;
if (this.options.links === true) {
anchor = document.createElement('a');
anchor.href = image.images['standard_resolution'].url;
anchor.rel = "lightbox";
anchor.appendChild(img);
fragment.appendChild(anchor);
} else {
fragment.appendChild(img);
}
}
document.getElementById(this.options.target).appendChild(fragment);
}
header = document.getElementsByTagName('head')[0];
header.removeChild(document.getElementById('instafeed-fetcher'));
instanceName = "instafeedCache" + this.unique;
delete window[instanceName];
}
if ((this.options.after != null) && typeof this.options.after === 'function') {
this.options.after.call(this);
}
return true;
};
Instafeed.prototype._buildUrl = function() {
var base, endpoint, final;
base = "https://api.instagram.com/v1";
switch (this.options.get) {
case "popular":
endpoint = "media/popular";
break;
case "tagged":
if (typeof this.options.tagName !== 'string') {
throw new Error("No tag name specified. Use the 'tagName' option.");
}
endpoint = "tags/" + this.options.tagName + "/media/recent";
break;
case "location":
if (typeof this.options.locationId !== 'number') {
throw new Error("No location specified. Use the 'locationId' option.");
}
endpoint = "locations/" + this.options.locationId + "/media/recent";
break;
case "user":
if (typeof this.options.userId !== 'number') {
throw new Error("No user specified. Use the 'userId' option.");
}
if (typeof this.options.accessToken !== 'string') {
throw new Error("No access token. Use the 'accessToken' option.");
}
endpoint = "users/" + this.options.userId + "/media/recent";
break;
default:
throw new Error("Invalid option for get: '" + this.options.get + "'.");
}
final = "" + base + "/" + endpoint;
if (this.options.accessToken != null) {
final += "?access_token=" + this.options.accessToken;
} else {
final += "?client_id=" + this.options.clientId;
}
final += "&count=" + this.options.limit;
final += "&callback=instafeedCache" + this.unique + ".parse";
return final;
};
Instafeed.prototype._genKey = function() {
var S4;
S4 = function() {
return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
};
return "" + (S4()) + (S4()) + (S4()) + (S4());
};
Instafeed.prototype._makeTemplate = function(template, data) {
var output, pattern, varName, varValue, _ref;
pattern = /(?:\{{2})([\w\[\]\.]+)(?:\}{2})/;
output = template;
while (pattern.test(output)) {
varName = output.match(pattern)[1];
varValue = (_ref = this._getObjectProperty(data, varName)) != null ? _ref : '';
output = output.replace(pattern, "" + varValue);
}
return output;
};
Instafeed.prototype._getObjectProperty = function(object, property) {
var piece, pieces;
property = property.replace(/\[(\w+)\]/g, '.$1');
pieces = property.split('.');
while (pieces.length) {
piece = pieces.shift();
if ((object != null) && piece in object) {
object = object[piece];
} else {
return null;
}
}
return object;
};
Instafeed.prototype._sortBy = function(data, property, reverse) {
var sorter;
sorter = function(a, b) {
var valueA, valueB;
valueA = this._getObjectProperty(a, property);
valueB = this._getObjectProperty(b, property);
if (reverse) {
if (valueA > valueB) {
return 1;
} else {
return -1;
}
}
if (valueA < valueB) {
return 1;
} else {
return -1;
}
};
data.sort(sorter.bind(this));
return data;
};
return Instafeed;})(); root = typeof exports !== "undefined" && exports !== null ? exports : window; root.Instafeed = Instafeed;}).call(this);
Any help with this issue would be GREATLY appreciated.
Thank You,
Jason

Categories

Resources