Simplify your stack and build anything. Or everything.
Build tomorrow’s web with a modern solution you truly own.
Code-based nature means you can build on top of it to power anything.
It’s time to take back your content infrastructure.

Rest API GET Media

default discord avatar
westhills.2 years ago
38

In my NextJS app I have this code to get the data:



const stringifiedQuery = qs.stringify( { where: { id: { equals: params.id, }, }, }, { addQueryPrefix: true }, ) const [portalFetch] = await Promise.all([ fetch(

${process.env.NEXT_PUBLIC_PAYLOAD_URL}/api/portals/${stringifiedQuery}

).then(res => res.json()),]); const portal = portalFetch.docs.length > 0 ? portalFetch?.docs ?? [] : null;

This is the result:


{ coverimage: '65d31092f125d8f649307943', packgeName: 'Couple Sessions', ... }

How can I retrive all the data of coverimage and not only the id?

  • default discord avatar
    anders22922 years ago
  • default discord avatar
    westhills.2 years ago

    nothing changes, or better, with depth 0 or 1 some elements are closed and begin to open to 2 but cover image no, it is always closed even up to 10

  • default discord avatar
    anders22922 years ago

    How is your access policy? If you use unauthenticated API call you need to make read public for the media collection as well.



    If you use authenticated API call you need to make sure the user can access the media collection.

  • default discord avatar
    westhills.2 years ago

    access: {


    read: ({ req }) => { return true },


    },



    for both collections



    In other collections it works well, only in this one I have this problem

  • default discord avatar
    anders22922 years ago

    Then Im not sure. You should share both collection definitions.

  • default discord avatar
    weetikveelman2 years ago

    What is the response you get when you try to fetch the coverimage itself through its collection?

  • default discord avatar
    westhills.2 years ago

    [


    {


    id: '65d31092f125d8f649307943',


    alt: 'Wedding in Como Lake',


    projectname: 'Pricing',


    filename: 'Wedding_Como_Lake.jpg',


    mimeType: 'image/jpeg',


    filesize: 1171785,


    width: 1365,


    height: 2048,


    sizes: { thumbnail: [Object] },


    createdAt: '2024-02-19T08:25:54.953Z',


    updatedAt: '2024-02-19T08:25:54.953Z',


    url: '/media/Wedding_Como_Lake.jpg'


    }


    ]



    The collection I'm trying to fetch:


    const Portals: CollectionConfig = { slug: 'portals', labels: { singular: 'Portal', plural: 'Portals', }, admin: { useAsTitle: 'clients', }, access: { read: ({ req }) => { return true }, }, versions: { drafts: true, }, fields: [ { type: 'tabs', // required tabs: [ // TAB 1 { label: 'Client Info', // required ... label: 'Pricing', // required description: 'Pricing.', fields: [ { name: 'packages', type: 'array', defaultValue: defaultValues.packages, labels: { singular: 'Package', plural: 'Packages', }, fields: [ { name: 'coverimage', type: 'upload', relationTo: 'media', label: 'Cover Image', required: false, index: true, }, ...

    Media collection:



    import { CollectionConfig } from 'payload/types' const Media: CollectionConfig = { slug: 'media', access: { read: ({ req }) => { return true}, }, upload: { staticURL: '/media', staticDir: 'media', imageSizes: [ { name: 'thumbnail', width: 400, height: 300, position: 'centre', } ], adminThumbnail: 'thumbnail', mimeTypes: ['image/*'], }, fields: [ { name: 'alt', label: 'Alt Text', type: 'text', }, { name: 'projectname', label: 'Project Name', type: 'text', }, { name: 'keywords', label: 'Keywords', type: 'text', }, ], } export default Media
  • default discord avatar
    weetikveelman2 years ago

    So it looks like you have access to the resource. If you are sure the depth is good then it sounds like a bug

  • default discord avatar
    anders22922 years ago

    Try to remove the «index: true». Maybe that is the bug?

  • default discord avatar
    westhills.2 years ago

    same 😦



    I've tried every depth from 0 to 20 , this is the result 😦



    May be something with the default values that I'm using? I've created a const with all the default value and coverimage is like this:



    `coverimage: {


    id: '65d31092f125d8f649307943',


    alt: 'Wedding in Como Lake',


    projectname: 'Pricing',


    filename: 'Wedding_Como_Lake.jpg',


    mimeType: 'image/jpeg',


    filesize: 1171785,


    width: 1365,


    height: 2048,


    sizes: {


    thumbnail: {


    width: 400,


    height: 300,


    mimeType: 'image/jpeg',


    filesize: 23553,


    filename: 'Wedding_Como_Lake-400x300.jpg',


    url: '/media/Wedding_Como_Lake-400x300.jpg'


    }


    },``

  • default discord avatar
    anders22922 years ago

    If you change the image to something else than the default?



    Should not the defaultvalue be just


    coverimage = ‘65d…’ ?

  • default discord avatar
    westhills.2 years ago

    if I change the image that's the same:


    { coverimage: '65a6bef64e8045e56241055d', packgeName: 'Weddings Package', packageDestination: 'Italian Destinations', packageDescription: [Object], options: [Array], id: '65d44809f57c2267e41504d3', addons: [], packageDescription_html: '<p>Two Photographers</p><p>Online gallery</p><p>Digital download + printing rights</p><p>Delivery in 6 months or less</p>' },

    I've also tried to set only the id but nothing change



    Maybe that's not the best way to do what I'm triyng to do.



    What I need is to set all the fields with some default values when the user create a new row. Then, the user, can modify that values or add new rows. The ideal for me is to create different set of values so the user can choose which one to use when create a new row. Should I create a custom plugin?



    At the moment I've simply manually create a const for the default values. The user can't choose the set of default values.



    Another way could be to create a row as a template then when a new row is created I set a fetch to check if that row exist and if is true it get all the info directly from the db.

  • default discord avatar
    anders22922 years ago

    Not sure what's going on. How do you set the default values into the field ?

  • default discord avatar
    westhills.2 years ago
    defaultValue: defaultValues.packages,

    -


    const defaultValues = { isPublished: false, clients: '', date: '', location: '', packages: [ { packgeName: 'Weddings Package', ...



    All other values works well.

  • default discord avatar
    anders22922 years ago

    Have you tried to remove the "defaultValue: defaultValues.packages," completely from your code and then create a new portal and see if that works? If that works you have at least scoped it down to be something with the default value.



    How is coverimage defined inside the packages array in the defaultValues ?

  • default discord avatar
    westhills.2 years ago

    same issue also if I select an image from payload interface 😦



    coverimage: { id: '65d31092f125d8f649307943', alt: 'Wedding in Como Lake', projectname: 'Pricing', filename: 'Wedding_Como_Lake.jpg', mimeType: 'image/jpeg', filesize: 1171785, width: 1365, height: 2048, sizes: { thumbnail: { width: 400, height: 300, mimeType: 'image/jpeg', filesize: 23553, filename: 'Wedding_Como_Lake-400x300.jpg', url: '/media/Wedding_Como_Lake-400x300.jpg' } }, createdAt: '2024-02-19T08:25:54.953Z', updatedAt: '2024-02-19T08:25:54.953Z', url: '/media/Wedding_Como_Lake.jpg' },
  • default discord avatar
    anders22922 years ago

    I think this is wrong. I think it should only be the id, because that is what is stored in that collection.


    So:


    coverimage: '65d31092f125d8f649307943'


    only instead of the complete object.



    But I'm not sure. I have not used defaultValue with upload fields before.



    As I say I think you should try to disable the defaultValues completely and then create a completely new fresh portal in the Portal collection where you select the image from payload admin. And see if that is fetching correclty.

  • default discord avatar
    westhills.2 years ago

    If I disable the defaultValues and create a new row with the upload fields I got always the same data. I've also tried to pass only the id to the upload field but again, the same problem.



    I don't understand why I don't have this problem with the other collections



    They have the same options, same code

  • default discord avatar
    anders22922 years ago

    Why is there an id field directly in the packages array element ?

  • default discord avatar
    westhills.2 years ago

    that's a log



    const stringifiedQuery = qs.stringify( { where: { id: { equals: params.id, depth: 3 }, }, }, { addQueryPrefix: true }, ) const [portalFetch] = await Promise.all([ fetch(

    ${process.env.NEXT_PUBLIC_PAYLOAD_URL}/api/portals/${stringifiedQuery}

    ).then(res => res.json()),]); const portal = portalFetch.docs.length > 0 ? portalFetch?.docs ?? [] : null; console.log(portal)
  • default discord avatar
    anders22922 years ago

    Can you share the complete packages array defintion ?



    Try setting the depth like this instead:



    const stringifiedQuery = qs.stringify(


    { where: { id: { equals: params.id }, }, },


    { depth: 3 },


    { addQueryPrefix: true },


    )

  • default discord avatar
    westhills.2 years ago

    now it's undefined



    `fields: [


    {


    name: 'packages',


    type: 'array',


    // defaultValue: defaultValues.packages,


    labels: {


    singular: 'Package',


    plural: 'Packages',


    },


    fields: [


    {


    name: 'coverimage',


    type: 'upload',


    relationTo: 'media',


    label: 'Cover Image',


    required: false,


    },


    {


    name: 'packgeName',


    type: 'text',


    },


    {


    name: 'packageDestination',


    type: 'text',


    },


    {


    name: 'packageDescription',


    type: 'richText',


    label: 'PackageDescription',


    editor: lexicalEditor({


    features: ({ defaultFeatures }) => [


    ...defaultFeatures,


    HTMLConverterFeature({}),


    ],


    }),


    },


    lexicalHTML('packageDescription', { name: 'packageDescription_html' }),


    {


    name: 'options',


    type: 'array',


    fields: [


    {


    name: 'title',


    type: 'text',


    },


    {


    name: 'price',


    type: 'text',


    },


    {


    name: 'startingFrom',


    type: 'checkbox',


    },


    {


    name: 'includes',


    type: 'richText',


    label: 'Includes',


    editor: lexicalEditor({


    features: ({ defaultFeatures }) => [


    ...defaultFeatures,


    HTMLConverterFeature({}),


    ],


    }),


    },


    lexicalHTML('includes', { name: 'includes_html' }),


    ],


    },


    ],


    },


    ],``

  • default discord avatar
    anders22922 years ago

    If you go to the API tab in payload admin panel. Does it show correctly there ?

  • default discord avatar
    westhills.2 years ago

    it works there!

  • default discord avatar
    anders22922 years ago

    const stringifiedQuery = qs.stringify(


    { where: { id: { equals: params.id }, }, depth: 3 },


    { addQueryPrefix: true },


    )



    ?

  • default discord avatar
    westhills.2 years ago

    same 😦

  • default discord avatar
    anders22922 years ago

    Since it works in API tab in portal I would check more into your query and the depth.

  • default discord avatar
    westhills.2 years ago

    I've also tried to do like this:



    const portalFetch = await fetch(

    ${process.env.NEXT_PUBLIC_PAYLOAD_URL}/api/portals/65d32345f125d8f649307b18?depth=3

    ).then(res =>


    res.json(),


    );



    but nothing change, any other test I can do?

  • default discord avatar
    anders22922 years ago

    Try to do the same as authenticated user to rule that out.



    You are sure NEXT_PUBLIC_PAYLOAD_URL is pointing to the correct instance? If you for example are running a local test environment ?

  • default discord avatar
    westhills.2 years ago

    yes, the env is correct, all the other data is correct.

  • default discord avatar
    anders22922 years ago

    Except for trying as an authenticated user I'm out of suggestions.



    Sorry

  • default discord avatar
    westhills.2 years ago

    thank you, I'm trying more with postman, and will try some auth with auth user



    I will let you updated



    resolved.


    I've just get rid off of the depth and it started to works 🧐



    const stringifiedQuery = qs.stringify( { where: { id: { equals: params.id}, }, }, { addQueryPrefix: true }, ) const portalFetch = await fetch(

    ${process.env.NEXT_PUBLIC_PAYLOAD_URL}/api/portals/${stringifiedQuery}`).then(res =>


    res.json(),


    );``

  • default discord avatar
    anders22922 years ago

    Maybe the depth was not high enough ?

  • default discord avatar
    westhills.2 years ago

    I think there is something wrong with the format of the string that I've still not understand. if I add ?depth=1 or 2 or anything else, it simply not found the row anymore :\

  • default discord avatar
    anders22922 years ago

    Maybe the extra slash is the problem here.



    The REST API should be used like:


    /api/portals?params when you want to query multiple


    /api/portals/id?params when you want to query by and id



    You are using /api/portals/?params that might be why it's giving unexpected results.



    Ref:

    https://payloadcms.com/docs/rest-api/overview
  • default discord avatar
    westhills.2 years ago

    thank you so much

  • default discord avatar
    anders22922 years ago

    Glad we found the root cause. It was irritating me.

  • default discord avatar
    dude_mcdudertonlast year

    this thread helped me a lot; was stuck on the same issue!

Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

Get dedicated engineering support directly from the Payload team.