2016-08-08 12 views
0

我正在使用標準化程序從不同的API端點具有相同的響應形狀。標準化程序創建單個實體的結果

const post = new Schema('posts'); 
 
const posts = arrayOf('post'); 
 

 
const listResponse = [ 
 
    {id: 1, text: 'post one'}, 
 
    {id: 2, text: 'post two'}, 
 
]; 
 
normalize(listResponse, posts); 
 

 
/* 
 
{ 
 
    entities: { 
 
    posts: { 
 
     1: {id: 1, text: 'post one'}, 
 
     2: {id: 2, text: 'post two'} 
 
    } 
 
    }, 
 
    result: [1, 2] 
 
} 
 
*/ 
 

 

 
const singleResponse = {id: 1, text: 'post one'}; 
 
normalize(singleResponse, post); 
 

 
/* 
 
{ 
 
    entities: { 
 
    posts: { 
 
     1: {id: 1, text: 'post one'} 
 
    } 
 
    }, 
 
    result: 1 
 
} 
 
*/

然後我想對待標準化響應不管它怎麼來的。

但事情是,對於單個項目我得到result: 1而不是數組result: [1],它會在我後面的代碼中導致一些問題。

現在我必須手動將result歸一化爲數組,但也許有更好的方法來做到這一點?

回答

5

在我的應用程序中,我對這種情況採用了兩種不同的操作FETCH_POSTFETCH_POSTS

但是,如果你有它的一些問題,你可以使用一個小黑客:

const singleResponse = {id: 1, text: 'post one'}; 
normalize([singleResponse], posts); 

當單正常化後的項目,我們可以簡單地把它換到數組和規範它作爲帖子的陣列。

+0

謝謝你,工作!我不想做兩件完全相同的動作。它使我的減速機縮短了兩倍。 –