2016-08-03 4 views
2

ページされたエンドポイントを逆シリアル化しようとしています。このエンドポイントの復帰要求がjs-data v3-ページングされたエンドポイントにメタ情報を保存する

{ 
    count: number, 
    next: string, 
    previous: string, 
    data: Array[Objects] 
} 

ようにfindAllを行うには、JS-データを使用しているとき私がいる問題に見える、それがデータストアにこのオブジェクトを注入しています。データ配列内のオブジェクトをストアに注入する必要があります。だから私はこのように見える私のアダプターのdeserializeメソッドを作った。

deserialize: (resourceConfig:any, response:any) => { 
    let data = response.data; 
    if (data && 'count' in data && 'next' in data && 'results' in data) { 
    data = data.results; 
    data._meta = { 
     count: response.data.count, 
     next: response.data.next, 
     previous: response.data.previous 
    }; 
    } 
    return data; 
} 

これは機能します。配列オブジェクトがデータストアに注入されています。しかし、メタ情報が失われています。

dataStore.findAll('User').then(r => console.log(r._meta)); // r._meta == undefined 

返されたオブジェクトにそのメタ情報を保存したいと思います。何か案は?

+0

あなたはページネーションはこれらの例にどのように扱われるかで見たことがありますか? https://github.com/js-data/js-data-examples https://plnkr.co/edit/ccMe5B – jdobry

答えて

2

これをv3で行うには、JSDataの ページネーションエンドポイントからの応答の処理を微調整するために、いくつかのメソッドをオーバーライドする必要があります。最も重要な2つの は、レスポンスのネストされたプロパティがレコード であり、どちらのネストされたプロパティがメモリ内ストアに追加されるべきかをJSDataに伝えることです(両方のケースで同じネストされたプロパティ である必要があります)。

例:

const store = new DataStore({ 
    addToCache: function (name, data, opts) { 
    if (name === 'post' && opts.op === 'afterFindAll') { 
     // Make sure the paginated post records get added to the store (and 
     // not the whole page object). 
     return DataStore.prototype.addToCache.call(this, name, data.results, opts); 
    } 
    // Otherwise do default behavior 
    return DataStore.prototype.addToCache.call(this, name, data, opts); 
    } 
}); 

store.registerAdapter('http', httpAdapter, { 'default': true }); 

store.defineMapper('post', { 
    // GET /posts doesn't return data as JSData expects, so we've got to tell 
    // JSData where the records are in the response. 
    wrap: function (data, opts) { 
    // Override behavior of wrap in this instance 
    if (opts.op === 'afterFindAll') { 
     // In this example, the Post records are nested under a "results" 
     // property of the response data. This is a paginated endpoint, so the 
     // response data might also have properties like "page", "count", 
     // "hasMore", etc. 
     data.results = store.getMapper('post').createRecord(data.results); 
     return data 
    } 
    // Otherwise do default behavior 
    return Mapper.prototype.wrap.call(this, data, opts); 
    } 
}); 

// Example query, depends on what your backend expects 
const query = { status: 'published', page: 1 }; 
posts.findAll(query) 
    .then((response) => { 
    console.log(response.results); // [{...}, {...}, ...] 
    console.log(response.page); // 1 
    console.log(response.count); // 10 
    console.log(response.hasMore); // true 
    }); 
+0

これは 'with'を使ってリレーションをロードするときには機能しません。 – altschuler

関連する問題