Exclude field from Local API

default discord avatar
slicxorlast year
7

Hello!



I'm using a Rich Text field with a hook to convert that into HTML and save it to another field. I'm then accessing the document via findByID but I don't need the JSON and it's making the data that's transported larger than it needs to be.



I'd like to stop the Rich Text field appearing in the document data but I can't see how to do it.



Is this not possible?

  • default discord avatar
    jarrod69420last year

    You could:


    - use GraphQL instead of REST


    - use an afterRead hook on the collection to omit the data from the response


    - add an afterRead hook to your html field and then delete the richText field from the response



    For the last option I think you could do something like this:


    {
      name: 'htmlField',
      type: 'text',
      hooks: {
        afterRead: [
          ({ siblingData, value }) => {
            delete siblingData.richTextField;
            return value;
          },
        ],
      },
    },
  • default discord avatar
    slicxorlast year

    Thanks for the reply.



    I'd rather use the Local API as it seems inefficient not to when working inside Payload. I tried your idea but it seems that this stops Payload itself from loading the content of that field inside the admin interface.



    I've been looking at the req property to see if there's a way to distinguish between Payload's calls and my calls to the Local API but it's huge and I haven't seen anything yet.



    Ideally I'd like to use a field hook to keep the logic with the field, and then add the hook to any field that I don't want in my API calls.

  • default discord avatar
    jarrod69420last year

    @alessiogr does this sound like a good use for context once that is merged?



    PR for reference:

    https://github.com/payloadcms/payload/pull/2796
  • discord user avatar
    alessiogr
    last year

    YEP! That should be a perfect use-case for context



    Once it's merged, you could use



    payload.findByID({
      ...
      context: {
        hideRichText: true,
      }
    })


    {
      name: 'htmlField',
      type: 'text',
      hooks: {
        afterRead: [
          ({ siblingData, value, context }) => {
            if (context.hideRichText) {
              delete siblingData.richTextField;
            }
            return value;
          },
        ],
      },
    },
  • default discord avatar
    slicxorlast year

    That's great, I've subscribed to the PR and hope to see the functionality soon!

Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

Get help straight from the Payload team with an Enterprise License.