Format json for return in a HasMany Smart Relationship

Hi everybody,

I would like to retrieve a user’s bank card list from the /user/{id}/cards route of my API. I was very successful in creating the smart relationship like this:

router.get('/user/:userId/relationships/cards', async (request, response, next) => {
  let requestOuranos = await axios.get(process.env.API_APP_URL + '/' + process.env.API_VERSION + '/user/' + request.params.userId + '/cards', {
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer ' + process.env.API_SECRET
    },
    responseType: 'json'
  }).then((result) => {
    return {
      status: result.status,
      data: result.data
    };
  }).catch((error) => {
    return {
      status: error.response.status,
      data: error.response.data
    };
  });
});

I get a json format like this :

[
  {
    id: 'card_1InRlOGhSnPh1ys0y5En3GrT',
    name: 'Ma CB',
    default: true,
    last4: '4242',
    expireMonth: 4,
    expireYear: 2024
  },
  {
    id: 'card_1InRpPGhSnPh1ys0XUtDkZaI',
    name: 'Mon AMEX',
    default: false,
    last4: '0005',
    expireMonth: 5,
    expireYear: 2045
  },
  {
    id: 'card_1InRoHGhSnPh1ys0mJxwAGwy',
    name: 'Ma CB Pro',
    default: false,
    last4: '4444',
    expireMonth: 4,
    expireYear: 2024
  }
]

I tried to return the json a little bit like this :

return response.send(json);

Obviously this does not work :’)

Can someone say me how to format and simply return this json ?
Thank’s

Hi @Benjamin,

As you want to display a has many relationships you are on the right path. You need to serialise your data, in order to display them on the front. Here’s some documentation the subject.

You need to create a smart collection for the purpose of serialising your data. For example in your case:

const { collection } = require('forest-express-sequelize');

collection('cards', {
  isSearchable: false,
  fields: [
  {
    field: 'id',
    type: 'String',
  }, {
    field: 'name',
    type: 'String',
    isFilterable: true,
  }, {
    field: 'default',
    type: 'Boolean',
  }, {
    field: 'last4',
    type: 'String',
  }, {
    field: 'expireMonth',
    type: 'Number',
  }, {
    field: 'expireYear',
    type: 'Number',
  }
  ],
});

Then you will be able to do the serialisation.

// You need to import RecordSerializer from forest-express-sequelize
const { RecordSerializer } = require('forest-express-sequelize');


...

   // Create a  RecordSerializer for the collection cards
   const serializer = new RecordSerializer({ name: 'cards' });

   // Seralize the data retrieve from  a  RecordSerializer for the collection cards
   const serializedRecords = await serializer.serialize(requestOuranos.data);

   // Finally send the serializedRecords to the client
   response.send(serializedRecords);

...

Let me know if it help. :slight_smile:
Best regards,
Morgan

Hi Morgan,
Thank you for your help.

Now I can get some data but not the one I want :confused:

As you can see in this photo :

I get the ID of the cards, but not the other information. And I don’t know why it shows me the user fields when I don’t need them.

Hi again,

I think there a problem with the .forestadmin-schema.json synchronisation. Have you restarted your agent ?

Can you give the your project name ? I will take a closer look.
Also, can you share me the implementation of the cards smart collection ?

Regards,
Morgan

Yes i have restart my agent, I also deleted my .forestadmin-schema.json but without successful.
My project name is : [dev-v2]Alfred
This is my cards smart collection :

const { collection } = require('forest-express-sequelize');

collection('cards', {
    isSearchable: false,
    actions: [],
    fields: [
        {
            field: 'id',
            type: 'String',
        }, {
            field: 'name',
            type: 'String',
            isFilterable: true,
        }, {
            field: 'default',
            type: 'Boolean',
        }, {
            field: 'last4',
            type: 'String',
        }, {
            field: 'expireMonth',
            type: 'Number',
        }, {
            field: 'expireYear',
            type: 'Number',
        }],
    segments: [],
});

Hi again,

Really wierd I tried on my side and I’m able to make it work with your mock data.

  1. How do you define the has many relationship in the user collection ? It should be something like this.
{
  field: 'cards',
  type: ['String'],
  reference: 'cards.id'
}
  1. Can you log the result.data object maybe it’s not a flat JSON (not the same you shared me).
  2. Can you look at the call /user/:userId/relationships/cards on your Network tab ? Add copy paste the response ?

I hope we will find the find the solution To be honest I’m a little bit stuck at this point. I don’t see what’s you are missing. :slightly_frowning_face:

Best regards,
Morgan

Okay that’s good !

I put user.id

fields: [{
    field: 'cards',
    type: ['String'],
    reference: 'user.id'
  }],

With cards it works.

Thank you !

1 Like

Really happy to hear that.

You’re welcome. Have a nice day.

Cheers,
Morgan

1 Like