Closed airpingu closed 10 years ago
Perhaps is better to use 3 methods:
Promise<index> insert(data); // fail if data exists, add and return index if data does not exist
Promise<index> add(data); // insert if data does not exist, and update if data exists
Promise<index> update(data); // update if data (primary key/index) exists and return the index, and return error if it does not exist
Sounds great! Will do it in this way. Thanks for the feedback.
Still have some concerns. I think the issue is, whether or not we should put the ID (primary key) in the data and APIs will automatically check it in the data. Maybe, we should make the ID more explicit as a function parameter:
Promise<void> update (any data, DataStoreKey id);
// 1. |id| must be specified:
// 1-a. If data doesn't exist with that |id|, return error.
// 1-b. If data exist with that |id|, update it by |data|.
Promise<DataStoreKey> add (any data, optional DataStoreKey id);
// |id| can be optional:
//
// 1. If |id| is specified:
// 1-a. if data exists with that |id|, update it by |data| and return |id|.
// 1-b. if data doesn't exist with that |id|, return error.
//
// 2. If |id| is NOT specified:
// 2-a. force to insert the |data| and return the newly generated id.
I made this at: https://github.com/airpingu/data-store-api/commit/e7402aed7232704977a8f75982e306f2e8576ab3
Updated page: http://airpingu.github.io/data-store-api/index.html#widl-DataStore-add-Promise-any-data-DataStoreKey-id and you can find the detailed steps below.
How do we get the id from given data, if the id is not part of the data? Let's say Messaging datastore defines a Message structure and Contacts datastore define a Contact structure. When I create a new Contact, the id is undefined. It will get updated when the data is insert'ed or add'ed. When the data exists, the id will be valid, so 'insert' will resolve to an error, and 'add' will do an update. So IMO what we need is defining a special value for id, denoting 'undefined'. It could be 0 for integer keys and '' for strings.
However, for the API itself you can choose to expose the id in a separate argument, too, for 'add' and 'update'.
Eventually, we're going to make: https://github.com/airpingu/data-store-api/issues/17. Close the one.
Please see https://github.com/airpingu/data-store-api/issues/2#issuecomment-32793575. But I'd still keep the original add() to do: