Open2

microCMSのコンテンツ情報を全件取得する。2022/03/15版

hanetsukihanetsuki
lib/microcms/index.ts
import {
  createClient,
  GetListRequest,
  MicroCMSListResponse,
} from 'microcms-js-sdk'
// コンテンツの型定義はこの中へ↓
import { Blog } from './types/blog'

// クライアントの作成
const client = createClient({
  serviceDomain: <serviceDomain>,
  apiKey: process.env.MICRO_CMS_API_KEY || '',
})

// APIを取りまとめるオブジェクト
export const microcmsFactory = {
  blogs: {
    getList: async (options?: Omit<GetListRequest, 'endpoint'>) => {
      return await client.getList<Blog>({ endpoint: 'blogs', ...options })
    },
  },
}

// microCMS系のutilsをまとめるclass
export class MicroCMSUtils {
  // 今回の主役
  static async getAllContents<T>(
    getListFn: (
      options?: Omit<GetListRequest, 'endpoint'> | undefined
    ) => Promise<MicroCMSListResponse<T>>,
    options?: Omit<GetListRequest, 'endpoint'>,
    limit = 10,
    offset = 0
  ): Promise<{ contents: (T & MicroCMSListContent)[]; totalCount: number }> {
    const data = await getListFn({
      queries: {
        limit,
        offset,
        ...options,
      },
    })

    if (data.offset + data.limit < data.totalCount) {
      const result = await MicroCMSUtils.getAllContents(
        getListFn,
        options,
        data.limit,
        data.offset + data.limit
      )
      return {
        contents: [...data.contents, ...result.contents],
        totalCount: result.totalCount,
      }
    }

    return {
      contents: data.contents,
      totalCount: data.totalCount,
    }
  }
}

(async () => {
  const result = await MicroCMSUtils.getAllContents(microcmsFactory.blogs.getList)
  console.log(result)
})()