简体   繁体   中英

Can Mockjax handle single IDs Api from Json file

I'm using Mockjax for the first time to mock a Restful API which will return a series of data given an id. Right now i have a json file that has several Items, and i would like to have a function inside Mockjax (or where necessary) to return only the queried ID. how can I achieve this?

current code :

$.mockjax({
    url: "/Api/Cases/{caseId}",
    proxy: "/mocks/cases nuevo.json",
    dataType: 'json',
    responseTime: [500, 800]
});

$.ajax({
    type: 'GET',
    url: '/Api/Cases/',
    data: {caseId: taskId},
    success: function(data){
        //use the returned
        console.log(data);
    }
});

current error:

GET http://localhost:8080/Api/Cases/?caseId=100 404 (Not Found)

Great question... yes, you can do this. But you'll have to write the functionality yourself using the response callback function and then making a "real" Ajax request for the file (instead of using the proxy option). Below I just make another $.ajax() call and since I have no mock handler setup for that endpoint, Mockjax lets it go through.

Note that setting up URL params is a little different than you suggest, here is what the mock setup looks like:

$.mockjax({
    url: /\/Api\/Cases\/(\d+)/,  // notice the regex here to allow for any ID
    urlParams: ['caseID'],       // This defines the first matching group as "caseID"
    responseTime: [500, 800],
    response: function(settings, mockDone) {
        // hold onto the mock response object
        var respObj = this;
        // get the mock data file
        $.ajax({
            url: 'mocks/test-data.json',
            success: function(data) {
                respObj.status = 200;
                // We can now use "caseID" off of the mock settings.urlParams object
                respObj.responseText = data[settings.urlParams.caseID];
                mockDone();
            },
            error: function() {
                respObj.status = 500;
                respObj.responseText = 'Error retrieving mock data';
                mockDone();
            }
        });
    }
});

There is one other problem with your code however, your Ajax call does not add the ID to the URL, it adds it to the query string. If you want to use that API endpoint you'll need to change your source code $.ajax() call as well. Here is the new Ajax call:

$.ajax({
    type: 'GET',
    url: '/Api/Cases/' + taskId, // this will add the ID to the URL
    // data: {caseId: taskId},   // this adds the data to the query string
    success: function(data){
        //use the returned
        console.log(data);
    }
});

Note that this presumes the mock data is something like:

{
    "13": { "name": "Jordan", "level": 21, "id": 13 },
    "27": { "name": "Random Guy", "level": 20, "id": 27 }
}

What I have ended up doing, is: I have left the $.mockjax function untouched, and i have manipulated the data inside the ajax request, using jquery's $.grep function as follows:

$.ajax({
        type: 'GET',
        url: '/Api/Cases/' + taskId,
        success: function(data){
        //note you have to parse the data as it is received as string
            data = JSON.parse(data);
            var result = $.grep(data, function(e){ return e.caseId ==  taskId; });
            //since i'm expecting only one result, i pull out the result on the 0 index position
            requestedData = result[0];
        }
});

The $.grep() method removes items from an array as necessary so that all remaining items pass a provided test see Jquery API , And since our test is that the caseId attribute of the element equals to the taksId variable sent, it will return all the elements that match the given Id, in this case, only one, this is why I've taken only the result on the 0 index position requestedData = result[0];

**Note: ** A more suited solution would be a mixture between what i've done and @jakerella 's answer, since their method implements the find element method inside the mockjacx function, and my function presumes a usual JSON response:

[{"caseId": 30,"name": "Michael"},{"caseId": 31,"name": "Sara"}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM