28 March 2018

How to implement custom BotStorage class for Microsoft BotFramework

Since launch, the MS BotFramework has been changing very rapidly. So rapidly, in fact, that I recently gave up trying to keep up with my handrolled Python, and embraced (sigh) their NodeJS SDK. At least now I won't have to worry when they break stuff, right ?
One of the most recent BF changes is the deprecation and eventual removal of the default persistence API. You are now supposed to either use one of the pre-built Azure services (paying $$), or provide your own implementation. In pure Microsoft style, they state that rolling your own is very easy... but never actually provide a sample or even tell you which interface should be implemented.
I had to scavenge through their code to figure it out (at least they opensource their stuff these days), but I thought I'd save others a bit of aggravation, and here it is:
var MyBotStorage = (function () {
    
    // optional constructor
    function MyBotStorage(options) {
        this.options = options;
    }
    
    MyBotStorage.prototype.getData = function (iBotStorageContext, 
                                                callback){
        // IBotStorageData interface
        var data = {
            userData: {},
            conversationData: {},
            privateConversationData: {}
        };
        // the callback MUST be invoked
        // signature: callback(Error, iBotStorageData )
        callback(null, data);
    }
    
    MyBotStorage.prototype.saveData = function (iBotStorageContext, 
                                                iBotStorageData, 
                                                errorCallback){
        // the callback MUST be invoked
        errorCallback(null);
    }
    
    return MyBotStorage;
}());

var botStorage = new MyBotStorage({});

var bot = new builder.UniversalBot(connector, function (session) {
            // your bot code here
    }).set('storage', botStorage); 
As you can see, it is indeed trivial, once you know how. It's sad that MS somehow, in the haste of deprecating their older interfaces, couldn't find the time to put this sample in their otherwise-extensive documentation. I suspect the fact that Azure is not mentioned anywhere might have something to do with it, but I'm sure I'm just assuming excessive malice and there is a perfectly-plausible explanation that does not involve greed. Or is there?

No comments: