2014-11-14 9 views
5

Próbuję zmodyfikować kod statusu http tworzenia.Jak zmienić kody statusu http w Strongloop Loopback

POST /api/users 
{ 
    "lastname": "wqe", 
    "firstname": "qwe", 
} 

Zwraca 200 zamiast 201

mogę zrobić coś takiego dla błędów:

var err = new Error(); 
err.statusCode = 406; 
return callback(err, info); 

Ale nie mogę znaleźć sposobu, aby zmienić kod statusu dla stworzenia.

znalazłem sposób utworzyć:

MySQL.prototype.create = function (model, data, callback) { 
    var fields = this.toFields(model, data); 
    var sql = 'INSERT INTO ' + this.tableEscaped(model); 
    if (fields) { 
    sql += ' SET ' + fields; 
    } else { 
    sql += ' VALUES()'; 
    } 
    this.query(sql, function (err, info) { 
    callback(err, info && info.insertId); 
    }); 
}; 
+0

Próbowałem to również zrozumieć. Bardziej kompleksowa dokumentacja byłaby miła :( – Jake

Odpowiedz

8

w wywołaniu remoteMethod można dodać funkcję do odpowiedzi bezpośrednio. Cel ten realizowany jest z opcją rest.after:

function responseStatus(status) { 
    return function(context, callback) { 
    var result = context.result; 
    if(testResult(result)) { // testResult is some method for checking that you have the correct return data 
     context.res.statusCode = status; 
    } 
    return callback(); 
    } 
} 

MyModel.remoteMethod('create', { 
    description: 'Create a new object and persist it into the data source', 
    accepts: {arg: 'data', type: 'object', description: 'Model instance data', http: {source: 'body'}}, 
    returns: {arg: 'data', type: mname, root: true}, 
    http: {verb: 'post', path: '/'}, 
    rest: {after: responseStatus(201) } 
}); 

Uwaga: Wydaje się, że strongloop wymusi 204 „No Content”, jeżeli wartość context.result jest falsey. Aby obejść ten problem, po prostu przekazuję pusty obiekt {} z żądanym kodem statusu.

+0

Dzięki! Działa! Ale teraz używam http://sailsjs.org/#/, o wiele bardziej elastycznego. – enguerran

1

Można określić domyślny kod odpowiedzi powodzenia dla metody zdalnej w parametrze http.

MyModel.remoteMethod(
    'create', 
    { 
    http: {path: '/', verb: 'post', status: 201}, 
    ... 
    } 
); 
Powiązane problemy