Monday 6 July 2015

Nativescript - Making the http request module into a re-usable generic function

I am currently working my way through developing a nativescript app. Developed by Telerik, it allows generation of native cross platform applications using Typescript or javascript. I am a fan of Typescript so I will be posting examples in that.

To be able to access JSON from a web server, there is the http module. I wanted to write my own helper class to simplify this down and make it more reusable.

The commonreferences section can be ignored, this is a helper module I use to store server names and particular urls. You could replace this with your server name.

If the call fails, it displays the details in a dialog box for debugging.

import http = require("http");
import commonReferences = require("../res/data/commonreferences");
var commonReferencesData: commonReferences.CommonReferences = commonReferences.data;
import dialogs = require("ui/dialogs");

export function request<T1, T2>(serviceName: string, content: T1, success: (result: T2) => void) {
    var request = JSON.stringify(content), url = commonReferencesData.BaseSiteUrl + commonReferencesData.ExerciseService + serviceName;
    http.request({
        url: url,
        method: "POST",
        headers: { "Content-Type": "application/json" },
        content: request
    }).then(function (response) {
        if (response.statusCode == 500) {
            dialogs.alert("Service : " + url + "\n\nParameters : " + request + "\n\nResponse : " + response.statusCode + ":" + response.content);
        }
        else {
            success(<T2> response.content.toJSON().d);
        }
    });
}


This can be called, as per the example below. As can be seen, you can define the expected input and output types.

import applicationSettingsHelper = require("../../helpers/applicationsettingshelper");
import textHelper = require("../../helpers/texthelper");
import pages = require("ui/page");
import observableHelper = require("../../helpers/observablehelper");
import httpHelper = require("../../helpers/httphelper");
import dialogHelper = require("../../dialogs/dialog/dialog-view-model");

export interface ForgotCallbackResult { userEmail: string }
export interface ForgotCallback { (result : ForgotCallbackResult, success: boolean): void };

export function display(page: pages.Page, action: ForgotCallback) {
    page.showModal("./dialogs/forgot/forgot-page", page, action);
}

export enum fields { userEmail };

interface ForgotUsernameOrPasswordRequest {
    userEmail: string;
    lang: string;
}

export class ForgotModel extends observableHelper.PopupModel<forgotcallbackresult> {
    constructor() {
        super(fields);

        this.addFields([
            {
                fieldName: fields.userEmail,
                validator: new textHelper.TextLengthValidation(applicationSettingsHelper.getUserEmail(), 1, 50, this.languageData.ForgotEmailBlank, this.languageData.ForgotEmailInvalid, "", "")
            }]);
    }

    public returnTrue() {

        this.setLoading(true);
        var forgotUsernameOrPasswordRequest: ForgotUsernameOrPasswordRequest = { userEmail: this.getValue(fields.userEmail), lang: applicationSettingsHelper.getLanguage() };
        httpHelper.request<forgotusernameorpasswordrequest,string>("/ForgotUsernameOrPassword", forgotUsernameOrPasswordRequest,(result: string) => {
            dialogHelper.displayInformation(this.page, result);
            this.returnValue = {
                userEmail: this.getValue(fields.userEmail)
            };

            this.returnResult(this.returnValue, true);
            this.setLoading(false);
        });

    }
}

export var forgotViewModel = new ForgotModel();


I will talk next about making better dialog boxes.

No comments:

Post a Comment