GetDutchie / brick

An intuitive way to work with persistent data in Dart

Home Page:https://getdutchie.github.io/brick/#/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Question (Perhaps Not an Issue) About topLevelKey

SubutaDan opened this issue · comments

I noticed some magic which I am trying to understand. The API I am using returns the list of my objects as the contents of a named array:

{
 "items": [
  {
   "kokoId": "63ebb313-251d-40ad-bc0e-9693489b6a85",
   "kokoName": "klambake",
   "latitude": 457.0,
   "longitude": 22.0,
. . .

Somehow Brick seems to have figured this out and is accessing and de-serializing my objects successfully. I looked at the Brick code and I though this must be the result the default topLevelKey behavior in rest_provider.dart. To try to confirm this theory I added a topLevelKey parameter to my RestRequest constructor invocation in my request transformer:

   return RestRequest(
        url: '/_ah/api/kokodokoapi/v1/kokos',
        topLevelKey: 'THERE_IS_NO_SUCH_KEY');
  }

but that didn't seem to affect the behavior. I tried both a key that didn't exist and a key that exists but isn't the correct topLevelKey.

Is it the topLevelKey feature that is making my code work?

Can you explain how to use the topLevelKey feature correctly?

Thank you for your help.

Hi @SubutaDan , the topLevelKey is only at the very, very top. There is a bit of magic indeed in the decoding process:

if (key != null && decoded[key] != null) {
  return decoded[key];
} else if (decoded is Map) {
  if (decoded.keys.length == 1) {
    return decoded.values.first;
  }
}

I tried both a key that didn't exist

Here, Brick determines that while a key is defined it does not exist. So it looks for a map in the response payload. Since it's {items: itemsArray} (a map with a length of 1), Brick chooses the first value of the first key and returns that.

a key that exists but isn't the correct topLevelKey.

This is functionally similar to the first case.

Is it the topLevelKey feature that is making my code work?

Yes and no. topLevelKey will make your code work if it's defined correctly, but it's also extremely permissive and forgiving.