按ID和区域设置获取内容

问题描述 投票:1回答:1

Contentful npm包提供对API的所有功能的访问。在我的情况下,我知道我想要的条目的ID,但需要检索非默认语言环境的数据,我看不到任何方式来传递语言环境选项。我的查询如下所示:

const { createClient } = require('contentful');

const contentfulClient = createClient({
  accessToken: 'xxxxxxxx',
  space: 'xxxxxxx',
});

const entry = contentfulClient
  .getEntry('xxxxxx')
  .catch(console.error);

我知道我可以做以下事情:

const data = await contentfulClient
  .getEntries({
    content_type: 'xxxxxx'
    locale: 'cy',
    'sys.id': xxxxx,
  })
  .catch(console.error);

const [entry] = data.items;

但这需要内容类型并返回一个条目数组,当我知道我想要的确切条目时,这似乎是反直觉的。我错过了什么吗?看起来像是合乎逻辑的事情。

javascript contentful
1个回答
2
投票

它没有在API documentation上这么说,但你绝对可以通过API使用locale=参数。

▶ curl -H "Authorization: Bearer $CONTENTFUL_ACCESS_TOKEN" https://cdn.contentful.com/spaces/$CONTENTFUL_SPACE_ID/entries/6wU8cSKG9UOE0sIy8Sk20G
{
  "sys": {
    "space": {
      "sys": {
        "type": "Link",
        "linkType": "Space",
        "id": "xxxx"
      }
    },
    "id": "6wU8cSKG9UOE0sIy8Sk20G",
    "type": "Entry",
    "createdAt": "2018-09-06T22:01:55.103Z",
    "updatedAt": "2018-10-08T19:26:59.382Z",
    "environment": {
      "sys": {
        "id": "master",
        "type": "Link",
        "linkType": "Environment"
      }
    },
    "revision": 14,
    "contentType": {
      "sys": {
        "type": "Link",
        "linkType": "ContentType",
        "id": "section"
      }
    },
    "locale": "en-US"
  },
  "fields": {
    "internalTitle": "test test test",
    ...

▶ curl -H "Authorization: Bearer $CONTENTFUL_ACCESS_TOKEN" https://cdn.contentful.com/spaces/$CONTENTFUL_SPACE_ID/entries/6wU8cSKG9UOE0sIy8Sk20G\?locale\=\*
{
  "sys": {
    "space": {
      "sys": {
        "type": "Link",
        "linkType": "Space",
        "id": "xxxx"
      }
    },
    "id": "6wU8cSKG9UOE0sIy8Sk20G",
    "type": "Entry",
    "createdAt": "2018-09-06T22:01:55.103Z",
    "updatedAt": "2018-10-08T19:26:59.382Z",
    "environment": {
      "sys": {
        "id": "master",
        "type": "Link",
        "linkType": "Environment"
      }
    },
    "revision": 14,
    "contentType": {
      "sys": {
        "type": "Link",
        "linkType": "ContentType",
        "id": "section"
      }
    }
  },
  "fields": {
    "internalTitle": {
      "en-US": "test test test"
    },
    ...

documentation for the contentful JS client说:

参数: 名称类型属性描述。 id字符串 query对象可选。 具有搜索参数的对象。在这种方法中,它只适用于locale

所以你要将语言环境添加为getEntry的第二个参数,如下所示:

const entry = contentfulClient
  .getEntry('xxxxxx', { locale: 'en-US' })
© www.soinside.com 2019 - 2024. All rights reserved.