Jeremy Love
Jeremy Love

Reputation: 179

contentful getEntries published data only

Is there a way to query the results to show only data that has been published and is not in draft state? I looked in the documentation and didn't quite find it.

This is what I currently have:

export const getAllPages = async (context?) => {
  const client = createClient({
    space: process.env.CONTENTFUL_SPACE_ID,
    accessToken: process.env.CONTENTFUL_ACCESS_TOKEN,
  });

  const pages = await client.getEntries({
    content_type: "page",
    include: 10,
    "fields.slug[in]": `/${context.join().replace(",", "/")}`,
  });

  return pages?.items?.map((item) => {
    const fields = item.fields;
    return {
      title: fields["title"],
    };
  });
};

Upvotes: 2

Views: 3421

Answers (3)

radar
radar

Reputation: 116

A solution that works for me is to use the Existence search parameter on the sys.publishedAt and sys.archivedAt fields, to filter for entries with a published date and also filter out archived entries simultaneously.

So, your code will look something like this:

async function getData() {
try{
    const res: any = await client.getEntries(
        {
            content_type: <content_type>,
            'sys.publishedAt[exists]': true, 
            'sys.archivedAt[exists]': false,
           
        }
    )
    
    return res.items
  } catch(err){
     console.error('fetching entries:', error);
  }
}

Upvotes: 4

Laiacy
Laiacy

Reputation: 1600

You can detect that the entries you get are in Published state:

function isPublished(entity) {
  return !!entity.sys.publishedVersion &&
    entity.sys.version == entity.sys.publishedVersion + 1
}

In your case, I would look for both Published and Changed:

function isPublishedChanged(entity) {
  return !!entity.sys.publishedVersion &&
    entity.sys.version >= entity.sys.publishedVersion + 1
}

Check the documentation:

https://www.contentful.com/developers/docs/tutorials/general/determine-entry-asset-state/

Upvotes: 1

harshil1712
harshil1712

Reputation: 191

To get only the published data you will need to use the Content Delivery API token. If you use the Content Preview API Token, you will receive both the published and draft entries.

You can read more about it here: https://www.contentful.com/developers/docs/references/content-delivery-api/

Upvotes: 0

Related Questions