IBM Worklight JSONStore — добавление и получение данных

Я использую WORLIGHT JSONstore. Я новичок в этом. Я пробовал искать, читать все документы, но не понял.

У меня есть одна страница входа, из которой я получаю некоторые данные json, которые я хочу сохранить, используя jsonstore. и получить это потом.

Я сделал адаптер jsonstore.

Json-Store-Impl.js

function getJsonStores(custData) {
var data = custData;
return data;
      //custdata is json 
}

 function addJsonStore(param1) {

var input = {
    method : 'put',
    returnedContentType : 'json',
    path : 'userInputRequired'
};


return WL.Server.invokeHttp(input);
}


function updateJsonStore(param1) {

var input = {
    method : 'post',
    returnedContentType : 'json',
    path : 'userInputRequired'
};


return WL.Server.invokeHttp(input);
}


function deleteJsonStore(param1) {


var input = {
    method : 'delete',
    returnedContentType : 'json',
    path : 'userInputRequired'
};


return WL.Server.invokeHttp(input);
}

после этого я создаю локальный магазин JSON.

famlCollection.js

;(function () {

WL.JSONStore.init({
    faml : {
        searchFields: {"response.mci.txnid":"string","response.mci.scrnseqnbr":"string","response.loginUser":"string","request.fldWebServerId":"string","response.fldRsaImageHeight":"string","request.fldRequestId":"string","request.fldTxnId":"string","response.fldDeviceTokenFSO":"string","response.fldRsaCollectionRequired":"string","response.datlastsuccesslogin":"string","response.fldRsaUserPhrase":"string","response.fldRsaAuthTxnId":"string","response.rc.returncode":"string","response.datcurrentlogin":"string","response.mci.deviceid":"string","response.customername":"string","request.fldDeviceId":"string","response.fldRsaUserStatus":"string","request.fldScrnSeqNbr":"string","response.fldRsaImageWidth":"string","request.fldLangId":"string","response.fldTptCustomer":"string","response.encflag":"string","response.rc.errorcode":"string","response.fldRsaImagePath":"string","response.mci.appid":"string","response.mci.requestid":"string","response.rc.errormessage":"string","response.mci.appserverid":"string","response.fldRsaCollectionType":"string","request.fldAppId":"string","response.fldRsaImageId":"string","request.fldLoginUserId":"string","response.mci.sessionid":"string","response.mci.langid":"string","response.mci.remoteaddress":"string","request.fldAppServerId":"string","response.mci.webserverid":"string","response.fldRsaImageText":"string","response.fldRsaEnrollRequired":"string","response.fldRsaActivityFlag":"string"},
        adapter : {
            name: 'JsonStore',
            replace: 'updateJsonStore',
            remove: 'deleteJsonStore',
            add: 'addJsonStore',
            load: {
                procedure: 'getJsonStores',
                params: [],
                key: 'faml'
            },
            accept: function (data) {
                return (data.status === 200);
            }
        }
    }
}, {
     password : 'PleaseChangeThisPassword'
})

.then(function () {
    WL.Logger.debug(['Take a look at the JSONStore documentation and getting started module for more details and code samples.',
        'At this point there is no data inside your collection ("faml"), but JSONStore is ready to be used.', 
        'You can use WL.JSONStore.get("faml").load() to load data from the adapter.',
        'These are some common JSONStore methods: load, add, replace, remove, count, push, find, findById, findAll.',
        'Most operations are asynchronous, wait until the last operation finished before calling the next one.',
        'JSONStore is currently supported for production only in Android and iOS environments.',
        'Search Fields are not dynamic, call WL.JSONStore.destroy() and then initialize the collection with the new fields.'].join('\n'));
})

.fail(function (errObj) {
    WL.Logger.ctx({pretty: true}).debug(errObj);
});

}());

Когда я нажал кнопку входа в систему, я вызываю getJsonStores следующим образом:

getJsonStores = function(){

    custData = responseData();
            var invocationData = {
                    adapter : "JsonStore",
                    procedure : "getJsonStores",
                    parameters : [custData],
                    compressResponse : true
            };
            //WL.Logger.debug('invoke msg  '+invocationData, '');
            WL.Client.invokeProcedure(invocationData, {
                onSuccess : sucess,
                onFailure : AdapterFail,                
                timeout: timeout
            });

    };

Я следил за эти шаги Это правильный путь? и как я могу проверить jsonstore работает локально или нет? и как я могу хранить свои jsondata в JSONStore? Где я должен инициализировать функцию wlCommonInit в проекте?

Пожалуйста, помогите мне.


person user3747168    schedule 17.06.2014    source источник


Ответы (1)


Откройте main.js и найдите функцию wlCommonInit, добавьте код инициализации JSONStore.

WL.JSONStore.init(...)

У вас уже есть адаптер, который возвращает данные, которые вы хотите добавить в JSONStore, вызывайте его в любое время после завершения инициализации.

WL.Client.invokeProcedure(...)

Внутри обратного вызова onSuccess функция, которая выполняется, когда вы успешно получаете данные от адаптера, начинаете использовать JSONStore API. Одним из высокоуровневых способов написания кода было бы, если коллекция пуста (API счетчика возвращает 0), затем добавить все документы в коллекцию.

WL.JSONStore.get(collectionName).count()
.then(function (countResult) {
  if(countResult === 0) {
    //collection is empty, add data
    WL.JSONStore.get(collectionName).add([{name: 'carlos'}, {name: 'mike'}])
    .then(function () {
      //data stored succesfully
    });
  }
}); 

Вместо добавления [{name: 'carlos'}, {name: 'mike'}] вы, вероятно, захотите добавить данные, возвращаемые адаптером.

Позже в вашем приложении вы можете использовать API поиска для возврата данных:

WL.JSONStore.get(collectionName).findAll()
.then(function (findResults) {
  //...
});

Существует также API поиска, который принимает запросы (например, {name: 'carlos'}), см. модуль "Начало работы" здесь и документацию здесь.

Стоит отметить, что JSONStore API является асинхронным, вы должны дождаться обратных вызовов, чтобы выполнить следующую операцию.

person cnandreu    schedule 17.06.2014