rest api fetch not working since 1.7.0

default discord avatar
itsjustchris
7 months ago
35

I have the following util for fetching posts which runs fine prior to 1.7.0. Now all I get is a response with zero docs.



My fetch for getting the post;



export async function getPostData(slug) { try { const response = await fetch(

${process.env.CMS_URL}/api/posts?where[slug][equals]=${slug}

); if (!response.ok) { throw new Error(

HTTP error! status: ${response.status}

); } const data = await response.json(); return data.docs[0]; } catch (error) { console.error(

Error fetching data: ${error}

); return []; } }
  • discord user avatar
    dribbens
    Payload Team
    7 months ago

    Does the API return status

    200

    and

    docs: []

    or are you seeing an error?

  • default discord avatar
    itsjustchris
    7 months ago

    status 200 and docs: []



    my post collection looks like this:



    import { CollectionConfig } from 'payload/types'; import slugify from 'slugify'; const Posts: CollectionConfig = { slug: 'posts', admin: { useAsTitle: 'title', defaultColumns: ['title', 'category', 'publishDate', 'tags', 'status'], group: 'Site Content', disableDuplicate: true, }, access: { read: ({ req: { user } }) => { if (user) { return true; } return { and: [ { publishDate: { less_than: new Date().toJSON(), }, _status: { equals: 'published', }, }, ], }; }, }, versions: { drafts: true, }, fields: [ { name: 'slug', type: 'text', unique: true, localized: true, index: true, admin: { readOnly: true, }, hooks: { beforeValidate: [ ({ req: { payload }, data }) => { if (payload) { if (data._status === 'draft') { return; } return slugify(data.title, { lower: true }); } }, ], }, }, { name: 'title', type: 'text', localized: true, }, { name: 'excerpt', label: 'Excerpt', type: 'text', }, { name: 'content', type: 'richText', admin: { elements: ['h2', 'h3', 'h4', 'link', 'ol', 'ul', 'indent'], }, }, { name: 'author', type: 'relationship', relationTo: 'users', defaultValue: ({ user }) => user.id, admin: { position: 'sidebar', }, }, { name: 'publishDate', type: 'date', admin: { position: 'sidebar', description: 'Posts will not be public until this date', }, defaultValue: () => new Date(), }, ], }; export default Posts;


    if i run payload 1.6.32 this is my response



    the same call using 1.7.1

    Screenshot_2023-04-20_at_4.01.30_PM.png
    Screenshot_2023-04-20_at_4.02.31_PM.png
  • discord user avatar
    dribbens
    Payload Team
    7 months ago

    I'll try and recreate this. We did change some things in our query construction, could be an edge case we missed. I'll add some tests on localized w/ drafts enabled and querying on the _status.



    Does it change anything if you are logged in or not? This would rule out if the change we made has to do with query constraints from the access control.

  • discord user avatar
    jmikrut
    Payload Team
    7 months ago

    i just tried to recreate using your exact access control, fields, and query - - and i can't recreate 😦



    i get the post back appropriately



    what is your default locale?



    does it work if you specify

    &locale=en

    or whatever locale you're looking to query?

  • default discord avatar
    itsjustchris
    7 months ago

    No difference whether I am logged in or not.



    I don't have a default locale set in my config, but I added one (en) and and ran the query with the

    &locale=en

    - both with and without a default locale set, and the results were the same. The exception being, that I get the same 200 status zero docs response with version 1.6.32 (and 1.7.0 & 1.7.1). With a default locale set.


    With out one set, and running the

    &locale=en

    param, I get the doc I am expecting in 1.6.32, not any version above that.

  • default discord avatar
    jakehopking
    7 months ago

    I've just upgraded to 1.7.1 and now my front end (nextjs) returns 404 pages for all routes that used to work.


    @jmikrut — What has changed that would cause this breaking change??



    FYI I have nextjs using payload's api in

    getServerSideProps


    Seems that fetch requests are still working (my header / footer is populated with correct data) but all page routes return 404 now 😢



    I don't have locales set either



    Reverting to 1.6.32 and all works again as expected



    I'll start a new topic - don't want to take over your thread @itsjustchris

  • default discord avatar
    itsjustchris
    7 months ago

    Further testing in my case reveals the issue to be only related to my posts collection. I have eliminated my app from the equation, and simply pass the query string into the browser.



    http://localhost:3000/api/posts?where[slug][equals]=test-post

    - using v1.6.32 returns the expected doc


    http://localhost:3000/api/posts?where[slug][equals]=test-post

    - using v1.7.1 returns zero docs


    http://localhost:3000/api/advertisers?where[slug][equals]=test-advertiser

    - using any version returns expected doc



    I checked out the db and there's nothing obvious to me why one would work and not the other.



    @jakehopking maybe try like I have done to try an narrow down the cause, perhaps we are looking at the same issue.

    db-screenshot.png
  • discord user avatar
    dribbens
    Payload Team
    7 months ago

    I also tried and couldn't reproduce. I am not giving up yet though.

  • default discord avatar
    jakehopking
    7 months ago

    @dribbens has anything changed on the payload api?


    I have for instance written a helper fn for all next pages with this:


    export const getCollectionSlug = async ({
      collection,
      slug,
      limit = 100,
      depth = 2,
    }) =>
      payload.find({
        collection,
        where: {
          slug: {
            equals: slug,
          },
        },
        limit,
        depth,
      });


    And I use it like this:


    export const getServerSideProps: GetServerSideProps = async (ctx) => {
      const slug = ctx.params?.slug
        ? (ctx.params.slug as string[]).join('/')
        : 'homepage';
    
      console.log(slug, process.env.WHICH_ENV);
    
      return await Promise.all([
        getCollectionSlug({ collection: 'pages', slug, depth: 3 }),
      ])
        .then(async (response) => {
          const [page] = response;
    
          page.docs[0].layout = await populateRelatedLayoutBlocks({
            layout: page?.docs[0]?.layout,
            page: page?.docs[0],
          });
    
          return {
            props: {
              page: page.docs[0],
              template: page.docs[0].template,
            },
          };
        })
        .catch((error) => {
          return {
            notFound: true, //redirects to 404.tsx page
          };
        });
    };
  • discord user avatar
    dribbens
    Payload Team
    7 months ago

    We added a feature to the querying code so that it validates incorrect paths, but it should have had no impact on working queries. We have test cases that seemingly do exactly what you and itsjustchris are doing. I'm wracking my brain and playing around with the test configs we use to reproduce this issue.

  • default discord avatar
    jakehopking
    7 months ago

    Happy to share access to my repo if it helps?

  • discord user avatar
    dribbens
    Payload Team
    7 months ago

    I've tried all the combinations I can think of:


    - use localization on the field being queried


    - versions { drafts: true }


    - access control returning boolean


    - access control returning a query



    That is probably the right next move, sure!



    Let's do it.



    I'm

    https://github.com/DanRibbens


    @itsjustchris Do you have localization on in your project? It appears that you have the field set to localized: true, but the screenshot of the data doesn't have locale keys like I'd expect.


    The only way I can reproduce the issue is when I have localization not enabled at the top of the config, but the fields themselves have localized: true.

  • default discord avatar
    itsjustchris
    7 months ago

    @dribbens nope! You're spot on - localization has never been added to the config, yet I have

    localization:true

    , which I think I inherited from some boilerplate. I removed that from the collection config, and it's working as I had hoped. What a fluke that it's been working this whole time 😅

  • discord user avatar
    dribbens
    Payload Team
    7 months ago

    Yeah, Payload should sanitize the config so that this can't happen. This was a hard issue to spot.



    Thanks for reporting!



    Just a heads up, you won't need to do anything to your projects. I opened a PR to bring the behavior back so that localized field querying in projects without localization will work the same as it did before 1.7.0.

    https://github.com/payloadcms/payload/pull/2542
  • default discord avatar
    itsjustchris
    7 months ago

    Nice. Thanks for your help! I'm glad to have assisted in making Payload that little bit better.

Open the post
Continue the discussion in Discord
Like what we're doing?
Star us on GitHub!

Star

Connect with the Payload Community on Discord

Discord

online

Can't find what you're looking for?

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