dimanche 19 avril 2015

Node.js and Spotify API - [Object] for all tracks in JSON playlist?

I'm new to Node.js and JSON in general and I'm trying to access each individual song in a playlist object returned by the spotify API. When I get the JSON object, it returns me a bunch of [Object] things in "items", which is where the tracks should be.


My code:



function iterPlaylists(callback)
{
console.log("POINT C");
listID = playlists[i].id;
console.log("Playlist name : "+ playlists[i].name + " Playlist ID: " + playlists[i].id );
callback();
}
//}, 800);

function getTrax(playlist)
{
iterPlaylists(function(){
spotifyApi.getPlaylist(id, listID)
.then(function(data) {
console.log('The playlist contains these tracks', data.body);
}, function(err) {
console.log('Something went wrong!', err);
});
});
}
setTimeout(function(){
getTrax(playlists);
}, 2000);


The output:



Playlist name : thug lif3 Playlist ID: 41moBc7H5bWrR3iiY0Zu9Q
The playlist contains these tracks { collaborative: false,
description: null,
external_urls: { spotify: 'http://ift.tt/1EfJxhY' },
followers: { href: null, total: 0 },
href: 'http://ift.tt/1OXuJGl',
id: '41moBc7H5bWrR3iiY0Zu9Q',
images:
[ { height: 640,
url: 'http://ift.tt/1EfJxi0',
width: 640 } ],
name: 'thug lif3',
owner:
{ external_urls: { spotify: 'http://ift.tt/1OXuJGo' },
href: 'http://ift.tt/1EfJxi2',
id: '1256443176',
type: 'user',
uri: 'spotify:user:1256443176' },
public: true,
snapshot_id: 'wjANf1rS9Nj1SFjRYTr4U2gKPtaYH0tq/5lZPorpDjCpSIg0rTxx5H+KIuFZebZp',
tracks:
{ href: 'http://ift.tt/1OXuJGr
00',
items: [ **[Object], [Object], [Object]** ],
limit: 100,
next: null,
offset: 0,
previous: null,
total: 3 },
type: 'playlist',
uri: 'spotify:user:1256443176:playlist:41moBc7H5bWrR3iiY0Zu9Q' }


Sorry for the messy block of output, but I'm really stumped on what to do here. Are these [object] things a sign of a nullity, or is there some way I can parse them and get the data from them? The API explorer on Spotify's website shows the actual track objects after "Items", so I'm confused as to why my app request isn't doing the same.


Ping to udp port of Team Speak 3 server with node.js

i have a Team Speak 3 server running in one machine. I need test if the Team Speak 3 is running, with node.js i implement a UDP client.



var dgram = require('dgram');
var message = new Buffer("ping ts server");
var client = dgram.createSocket("udp4");

client.send(message, 0, message.length, 55223, "127.0.0.1",
function (err, bytes) {
if (err) {
console.log('Not running !!');
throw err;
}

console.log("Wrote " + bytes + " bytes to socket.");
});


But when i run this code, the udp client in node ever say to me that the server is running, including when i stop the server.


Please anyone can help me?


How can I query MongoDB in a blocking way ? (not sure if this is the right way though)

Let me introduce my problem : I'm currently developing a web app using Node.js, Express and MongoDB (mongoose driver), and I would like, when the user requests /save, to generate an unique ID (made of random letters and digits) in order to redirect the request to /save/id.


Therefore I want my /save route to query MongoDB for a list of existing IDs, and generate a random ID which is not present in the list.


Any idea on how to do that ?


Various Regex Validation

I'm new to regex. I have an array (call it arr1) with assorted values. I am trying to validate that it has the following format for its elements with arr1[x] provided as an example



arr1[x] = "item1, item2, item3, item4, item5":

item 1 - "abcdef" (variable number of letters) or "abcdef asdf" (variable number of letters separated by one whitespace character)
item 2 - "abcdef" (variable number of letters) or "abcdef asdf" (variable number of letters separated by one whitespace character)
item 3 - "12345678" (eight digits)
item 4 - "123 456 7890" (telephone number with 3 digits followed by 3 digits followed by 4 digits with two whitespace characters as shown)


Here is a snippet of what I have for phone number validation (not sure how the second line works - got it from a different SO thread):



function f(s) {
var s2 = (""+s).replace(/\D/g, '');
var m = s2.match(/^(\d{3})(\d{3})(\d{4})$/);
}


Thanks in advance for any assistance.


samedi 18 avril 2015

Mongoose: sort and filter results from multiple collections

Let's say I have multiple collections containing data, now I want to search and filter data from all those collections, what would be the best way to do this?


Currently I need to run a query for each individual collection, then merge the results, filter them again, and reduce the length of the array depending on the limit.


Is there an easier way to do this?


Using supertest and co to validate database content after request

I want to write a test to update a blog post (or whatever): * Insert a blog post in a database * Get the id the blog post got in MongoDb * POST an updated version to my endpoint * After the request have finished: check in the database that update has been done


Here's this, using koa:



var db = require('../lib/db.js');
describe('a test suite', function(){
it('updates an existing text', function (done) {
co(function * () {
var insertedPost = yield db.postCollection.insert({ title : "Title", content : "My awesome content"});
var id = insertedPost._id;
var url = "/post/" + id;
var updatedPost = { content : 'Awesomer content' };

request
.post(url)
.send(updatedTextData)
.expect(302)
.expect('location', url)
.end(function () {
co(function *() {
var p = yield db.postCollection.findById(id);
p.content.should.equal(updatedPost.content);
console.log("CHECKED DB");
})(done());
});
});
});
});


I realize that there's a lot of moving parts in there, but I've tested all the interactions separately. Here's the db-file I've included (which I know works fine since I use it in production):



var monk = require('monk');
var wrap = require('co-monk');

function getCollection(mongoUrl, collectionName) {
var db = monk(mongoUrl);
return wrap(db.get(collectionName));
};

module.exports.postCollection = getCollection([SECRET MONGO CONNECTION], 'posts');


The production code works as intended. This test passes but it seems, to me, like the co-function in the .end()-clause never is run... but the done() call gets made. No "CHECKED DB" is being printed, at least.


I've tried with "done()" and "done" without. Sometimes that works and sometimes not. I've tried to move the check of the database outside the request... but that just hangs, since supertest wants us to call done() when we are completed.


All of this leaves me confused and scared (:)) - what am I doing wrong here.


authwithcustomtoken not working

In my project I am writing e2e tests in node.js and I have a test firebase I am using. So I create a token in node before each describe in the test runs and then I send it to the front end(angular.js) and then I use the authWithCustomToken function to authenticate the person.


The problem is for some reason it isn't even calling the function because I put a console.log statement in the callback and every time my code runs it enters the if $location.search condition but the console.log doesn't print out anything. I dont seem to know what the problem is.



var Firebase = require('firebase');
var FirebaseTokenGenerator = require('firebase-token-generator');
var rootRef = new Firebase('https://xxxxx');
var data = require('./data_helper.js');

rootRef.child('users').set(data.users[0]);

var credentials = {
nonAdmin: {
uid: 'google',
email: 'xxxx'
},
admin: {
uid: 'google',
email: 'xxxxx'
}
};


var logInAndThen = function(options) {
var secret = 'sdmdfmdsjwdsjwjwwewewe';
var tokenGenerator = new FirebaseTokenGenerator(secret);
var token = tokenGenerator.createToken(credentials[options.userType || 'admin']);

browser.get('/login?token=' + token);

var alertDiv = by.className('alert');
//browser.wait(function(){});
var waitOnFirebase = browser.wait(function() {
return browser.isElementPresent(alertDiv);
});

waitOnFirebase.then(function(data) {
console.log('-------', data);
options.cb(data);
});
};

module.exports = logInAndThen;


--------- FRONT END ANGULAR CODE PUT IN APPLICATION.RUN---------------------



if($location.search().token) {
console.log(Refs.root.toString());
Refs.root.authWithCustomToken($location.search().token, function(err, authData) {
console.log(err,authData);
}, {scope: 'email'});
}


I would appreciate it if someone could help me with this