Freitag, 28. August 2015

Website reminder extension

Last week I found a new cool project on product hunt - http://requestforstartup.co/ I really like the idea and I look at the list almost every day. On Monday I saw a tweet by MohammadRizeg who requested a browser add-on, which would remind the user to visit a webpage later after defined time period or at certain time. Since I'm a bit familiar with chrome browser extension API, I thought "Why not?" And here we go, after two coding evenings instead of watching tv series  the "Web Reminder" extension is ready and published on the chrome webstore.

Donnerstag, 16. Juli 2015

Auto increment attribute for sails-mongo waterline.

Sometimes there is a need to have an auto increment field in your MongoDb collection. There are different strategies, how you can create auto increment sequences with mongo. You can find the general information in the official documentationhttp://docs.mongodb.org/manual/tutorial/create-an-auto-incrementing-field/
Here is an adaptation of the first approach for sails.js waterline ORM, which uses counter collection. First you have to create a Sequence Model and implement a get next method.
module.exports = {
    attributes : {
        num : {
            type : "integer"
        },
    },

    next : function (id, cb) {

        Sequence.native(function (err, col) {

            col.findAndModify(
                { _id: id },
                [['_id', 'asc']],
                {$inc: { num : 1 }},
                { new: true, upsert : true}
                , function(err, data) {

                    cb(err, data.value.num);
                });

        });

    },
};
Since waterline doesn't support findAndModify functionality of mongodb, you have to make use of native driver method. It looks bit weird, but it works. More about it here.
And then you can just call the Sequence.next() in the beforeCreate lifecycle callback method of your model to get next auto increment value for the new collection document.
// Model Order, for Example.
module.exports = {

    attributes: {

        number: {
            type: "integer"
        },
        // other attributes
    },

    // add auto increment value for "number" before create a document
    beforeCreate : function (values, cb) {

        // add seq number, use
        Sequence.next("order", function(err, num) {

            if (err) return cb(err);

            values.number = num;

            cb();
        });
    }

    // your other methods ...
};

Mittwoch, 10. Juni 2015

findAndModify MongoError: need remove or update. Node native driver pitfall

I'm going to migrate one of my projects to the sails.js framework, which seems to be really great, it is worth a dedicated post, but right now I would like to write about a pitfall, you may trap in to, like me while changing from mongojs to waterline or other data object mapper. All the basic functionality is working as expected, but if you need some custom features you need to query using the native driver. So for example, I just wanted to implement a custom method for updating an object using  findAndModify() query.

Dienstag, 2. Juni 2015

Mongo Modulus vs Mongolab

I like Modulus.io, their PaaS is great. Simple and scaleable, perfect for bootstrapping new projects from scratch with zero own infrastructure, just deploy your code in to the the cloud of your choice and that's it. Since we do not have a dedicated server admin in our team and I didn't have time to maintain the node servers, cache and mongo clusters, we decided to switch to a "platform as a service" hosting. I chose Modulus (not Heroku) because it was dedicated for node applications, now you can deploy php and java apps as well. The interface of the dashboard is minimalistic and some features like slow responses list should be extendable, but it's ok so far. The migration from AWS environment was quite easy: dump and restore mongo database, switch domain names, deploy the app and voilà, the app runs on new platform. Ok, additionally we had to setup a memcached and redis instances on Redislabs.com, but it is not that important for now.    

Donnerstag, 2. April 2015

MongoDB set value of the field to the existing field value

Today I wanted to cleanup the user database by removing, renaming some fields. Since long names in a document oriented database like mongoDB takes some storage size we are using short names with prefixes like "d_c" for date of creation "d_u" for date of last update and so on. So I was going to rename some old field names, bit first I wanted to do a copy of a field so I can drop the old version later once the code is changed and deployed. It's really easy to copy a value, if you use (My)SQL. You can just run a query like this:

UPDATE table SET field1 = field2 

and that's it. Of course you need to alter the table and add the field definition first. So my intuitive attempt was to do the same way with mongo db. Here we go:

db.collection.update({foo : bar}, {$set : {field1 : field2}});

But it results in "ReferenceError: field2 is not defined" Ok, I thought may be there is a possibility to reference the current object like "this"... But unfortunately not. You have to implement a simple helper script in order to update every document:

db.collection.update({foo : bar}).snapshot().forEach(function(row) {
    row.field1 = row.field2;
    db.collection.save(row);
}); 


The snapshot command is optional, but it is recommended to use it, if you're updating a live database;) see details http://docs.mongodb.org/manual/reference/method/cursor.snapshot/



Mittwoch, 18. Februar 2015

Mobile App Authentifizierung. Learnings & Best Practice.

Die erste Version unserer App war eine Art Video Messenger. Wir haben uns deshalb bei der Authentifizierung ziemlich genau an die von WhatsApp orientiert. Das heißt die Mobilfunk Nummer ist die unique Identifizierung vom Benutzer und muss vor der Nutzung der App verifiziert werden. Ich muss sagen das war eine ziemlich nervige Geschichte. Danach haben wir uns aber für eine mehr benutzerfreundliche Variante entschieden, die ich auch kurz beschreiben werde.

Samstag, 7. Februar 2015

Береговая Рыбалка на Канарах Ч. 2

Погода на Тенерифе довольно интересна, я бы назвал её так - это самая постоянная, быстро меняющаяся погода. С раннего утра может быть всё затянуто тёмными, грозовыми тучами, а через пару часов ясно и лишь лёгкий бриз. Хотя часто тучи "цепляются" за горный массив и весят шапкой над центром острова. A вообще климат на острове, по крайней мере по мнению НАСА является самым благоприятным для человека на всей планете, самое большое количество солнечных, ясных дней и в тоже время средняя температура в году около 23 градусов Цельсия.  Поэтому на вершине Тейде, которая является между прочим самой высокой горой Испании, находится одна из обсерваторий, где можно наблюдать вот такие космические пейзажи.

Freitag, 23. Januar 2015

Wifi or not wifi. You are not welcome here!

Etwas "dramatisches" zur Abwechslung. Ich wollte eigentlich nie über Politik und ähnliches schreiben. Obwohl das, was passiert ist, glaube ich weniger mit Politik zu tun hat als mit dem, was in den Köpfen von manchen Menschen zu tief drin steckt.

Donnerstag, 22. Januar 2015

Uploading video to facebook with node.js

Another topic regarding Facebook API and Node.js or JavaScript SDK. While developing the PQ App, we wanted to make it possible for the users to optionally publish the video on the Fb feed. Sounds like a simple action, but it isn't that trivial.

Mittwoch, 21. Januar 2015

Obtaining long lived facebook access token with superagent

Right now we are integrating Fb login and some sharing stuff in our app. The sharing part should be done on the server side, so we need to get a long lived access token in order to make Facebook graph API calls on behalf of the user. Here is a small function, which exchanges the short lived token for a longed lived one using superagent library.