npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

microcms-js-sdk

v3.1.2

Published

JavaScript SDK Client for microCMS.

Downloads

104,416

Readme

microCMS JavaScript SDK

It helps you to use microCMS from JavaScript and Node.js applications.

Tutorial

See the official tutorial.

Getting started

Installation

Node.js

$ npm install microcms-js-sdk

or

$ yarn add microcms-js-sdk

[!IMPORTANT] v3.0.0 or later requires Node.js v18 or higher.

Browser(Self-hosting)

Download and unzip microcms-js-sdk-x.y.z.tgz from the releases page. Then, host it on any server of your choice and use it. The target file is ./dist/umd/microcms-js-sdk.js.

<script src="./microcms-js-sdk.js"></script>

Browser(CDN)

Please load and use the URL provided by an external provider.

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/microcms-js-sdk.min.js"></script>

or

<script src="https://cdn.jsdelivr.net/npm/microcms-js-sdk/dist/umd/microcms-js-sdk.min.js"></script>

[!WARNING] The hosting service (cdn.jsdelivr.net) is not related to microCMS. For production use, we recommend self-hosting on your own server.

Contents API

Import

Node.js

const { createClient } = require('microcms-js-sdk'); // CommonJS

or

import { createClient } from 'microcms-js-sdk'; //ES6

Usage with a browser

<script>
  const { createClient } = microcms;
</script>

Create client object

// Initialize Client SDK.
const client = createClient({
  serviceDomain: 'YOUR_DOMAIN', // YOUR_DOMAIN is the XXXX part of XXXX.microcms.io
  apiKey: 'YOUR_API_KEY',
  // retry: true // Retry attempts up to a maximum of two times.
});

API methods

The table below shows each API method of microCMS JavaScript SDK and indicates which API format (List Format or Object Format) they can be used with using ✔️.

| Method | List Format | Object Format | |-------------------|-------------|---------------| | getList | ✔️ | | | getListDetail | ✔️ | | | getObject | | ✔️ | | getAllContentIds | ✔️ | | | getAllContents | ✔️ | | | create | ✔️ | | | update | ✔️ | ✔️ | | delete | ✔️ | |

[!NOTE]

  • ✔️ in "List Format" indicates the method can be used when the API type is set to List Format.
  • ✔️ in "Object Format" indicates the method can be used when the API type is set to Object Format.

Get content list

The getList method is used to retrieve a list of content from a specified endpoint.

client
  .getList({
    endpoint: 'endpoint',
  })
  .then((res) => console.log(res))
  .catch((err) => console.error(err));

Get content list with parameters

The queries property can be used to specify parameters for retrieving content that matches specific criteria. For more details on each available property, refer to the microCMS Documentation.

client
  .getList({
    endpoint: 'endpoint',
    queries: {
      draftKey: 'abcd',
      limit: 100,
      offset: 1,
      orders: 'createdAt',
      q: 'Hello',
      fields: 'id,title',
      ids: 'foo',
      filters: 'publishedAt[greater_than]2021-01-01T03:00:00.000Z',
      depth: 1,
    }
  })
  .then((res) => console.log(res))
  .catch((err) => console.error(err));

Get single content

The getListDetail method is used to retrieve a single content specified by its ID.

client
  .getListDetail({
    endpoint: 'endpoint',
    contentId: 'contentId',
  })
  .then((res) => console.log(res))
  .catch((err) => console.error(err));

Get single content with parameters

The queries property can be used to specify parameters for retrieving a single content that matches specific criteria. For more details on each available property, refer to the microCMS Documentation.

client
  .getListDetail({
    endpoint: 'endpoint',
    contentId: 'contentId',
    queries: {
      draftKey: 'abcd',
      fields: 'id,title',
      depth: 1,
    }
  })
  .then((res) => console.log(res))
  .catch((err) => console.error(err));

Get object format content

The getObject method is used to retrieve a single object format content

client
  .getObject({
    endpoint: 'endpoint',
  })
  .then((res) => console.log(res))
  .catch((err) => console.error(err));

Get all contentIds

The getAllContentIds method is used to retrieve all content IDs only.

client
  .getAllContentIds({
    endpoint: 'endpoint',
  })
  .then((res) => console.log(res))
  .catch((err) => console.error(err));

Get all contentIds with filters

It is possible to retrieve only the content IDs for a specific category by specifying the filters.

client
  .getAllContentIds({
    endpoint: 'endpoint',
    filters: 'category[equals]uN28Folyn',
  })
  .then((res) => console.log(res))
  .catch((err) => console.error(err));

Get all contentIds with draftKey

It is possible to include content from a specific draft by specifying the draftKey.

client
  .getAllContentIds({
    endpoint: 'endpoint',
    draftKey: 'draftKey',
  })
  .then((res) => console.log(res))
  .catch((err) => console.error(err));

Get all contentIds with alternateField

The alternateField property can be used to address cases where the value of a field other than content ID is used in a URL, etc.

client
  .getAllContentIds({
    endpoint: 'endpoint',
    alternateField: 'url',
  })
  .then((res) => console.log(res))
  .catch((err) => console.error(err));

Get all contents

The getAllContents method is used to retrieve all content data.

client
  .getAllContents({
    endpoint: 'endpoint',
  })
  .then((res) => console.log(res))
  .catch((err) => console.error(err));

Get all contents with parameters

The queries property can be used to specify parameters for retrieving all content that matches specific criteria. For more details on each available property, refer to the microCMS Documentation.

client
  .getAllContents({
    endpoint: 'endpoint',
    queries: { filters: 'createdAt[greater_than]2021-01-01T03:00:00.000Z', orders: '-createdAt' },
  })
  .then((res) => console.log(res))
  .catch((err) => console.error(err));

Create content

The create method is used to register content.

client
  .create({
    endpoint: 'endpoint',
    content: {
      title: 'title',
      body: 'body',
    },
  })
  .then((res) => console.log(res.id))
  .catch((err) => console.error(err));

Create content with specified ID

By specifying the contentId property, it is possible to register content with a specified ID.

client
  .create({
    endpoint: 'endpoint',
    contentId: 'contentId',
    content: {
      title: 'title',
      body: 'body',
    },
  })
  .then((res) => console.log(res.id))
  .catch((err) => console.error(err));

Create draft content

By specifying the isDraft property, it is possible to register the content as a draft.

client
  .create({
    endpoint: 'endpoint',
    content: {
      title: 'title',
      body: 'body',
    },
    // Available with microCMS paid plans
    // https://microcms.io/pricing
    isDraft: true,
  })
  .then((res) => console.log(res.id))
  .catch((err) => console.error(err));

Create draft content with specified ID

By specifying the contentId and isDraft properties, it is possible to register the content as a draft with a specified ID.

client
  .create({
    endpoint: 'endpoint',
    contentId: 'contentId',
    content: {
      title: 'title',
      body: 'body',
    },
    // Available with microCMS paid plans
    // https://microcms.io/pricing
    isDraft: true,
  })
  .then((res) => console.log(res.id))
  .catch((err) => console.error(err));

Update content

The update method is used to update a single content specified by its ID.

client
  .update({
    endpoint: 'endpoint',
    contentId: 'contentId',
    content: {
      title: 'title',
    },
  })
  .then((res) => console.log(res.id))
  .catch((err) => console.error(err));

Update object format content

When updating object content, use the update method without specifying a contentId property.

client
  .update({
    endpoint: 'endpoint',
    content: {
      title: 'title',
    },
  })
  .then((res) => console.log(res.id))
  .catch((err) => console.error(err));

Delete content

The delete method is used to delete a single content specified by its ID.

client
  .delete({
    endpoint: 'endpoint',
    contentId: 'contentId',
  })
  .catch((err) => console.error(err));

TypeScript

If you are using TypeScript, use getList, getListDetail, getObject. This internally contains a common type of content.

Response type for getList method

type Content = {
  text: string,
};
/**
 * {
 *  contents: Content[]; // This is array type of Content
 *  totalCount: number;
 *  limit: number;
 *  offset: number;
 * }
 */
client.getList<Content>({ /* other */ })

Response type for getListDetail method

type Content = {
  text: string,
};
/**
 * {
 *  id: string;
 *  createdAt: string;
 *  updatedAt: string;
 *  publishedAt?: string;
 *  revisedAt?: string;
 *  text: string; // This is Content type.
 * }
 */
client.getListDetail<Content>({ /* other */ })

Response type for getObject method

type Content = {
  text: string,
};
/**
 * {
 *  createdAt: string;
 *  updatedAt: string;
 *  publishedAt?: string;
 *  revisedAt?: string;
 *  text: string; // This is Content type.
 * }
 */

client.getObject<Content>({ /* other */ })

Response type for getAllContentIds method

/**
 * string[] // This is array type of string
 */
client.getAllContentIds({ /* other */ })

Create method with type safety

Since content will be of type Content, no required fields will be missed.

type Content = {
  title: string;
  body?: string;
};

client.create<Content>({
  endpoint: 'endpoint',
  content: {
    title: 'title',
    body: 'body',
  },
});

Update method with type safety

The content will be of type Partial<Content>, so you can enter only the items needed for the update.

type Content = {
  title: string;
  body?: string;
};

client.update<Content>({
  endpoint: 'endpoint',
  content: {
    body: 'body',
  },
});

CustomRequestInit

Next.js App Router

You can now use the fetch option of the Next.js App Router as CustomRequestInit. Please refer to the official Next.js documentation as the available options depend on the Next.js Type file.

Functions: fetch | Next.js

const response = await client.getList({
  customRequestInit: {
    next: {
      revalidate: 60,
    },
  },
  endpoint: 'endpoint',
});

AbortController: abort() method

You can abort fetch requests.

const controller = new AbortController();
const response = await client.getObject({
  customRequestInit: {
    signal: controller.signal,
  },
  endpoint: 'config',
});

setTimeout(() => {
  controller.abort();
}, 1000);

Management API

Import

Node.js

const { createManagementClient } = require('microcms-js-sdk'); // CommonJS

or

import { createManagementClient } from 'microcms-js-sdk'; //ES6

Usage with a browser

<script>
  const { createManagementClient } = microcms;
</script>

Create client object

const client = createManagementClient({
  serviceDomain: 'YOUR_DOMAIN', // YOUR_DOMAIN is the XXXX part of XXXX.microcms.io
  apiKey: 'YOUR_API_KEY',
});

Upload media

Media files can be uploaded using the 'POST /api/v1/media' endpoint of the Management API.

Node.js

// Blob
import { readFileSync } from 'fs';

const file = readFileSync('path/to/file');
client
  .uploadMedia({
    data: new Blob([file], { type: 'image/png' }),
    name: 'image.png',
  })
  .then((res) => console.log(res))
  .catch((err) => console.error(err));

// or ReadableStream
import { createReadStream } from 'fs';
import { Stream } from 'stream';

const file = createReadStream('path/to/file');
client
  .uploadMedia({
    data: Stream.Readable.toWeb(file),
    name: 'image.png',
    type: 'image/png',
  })
  .then((res) => console.log(res))
  .catch((err) => console.error(err));

// or URL
client
  .uploadMedia({
    data: 'https://example.com/image.png',
    // name: 'image.png', ← Optional
  })
  .then((res) => console.log(res))
  .catch((err) => console.error(err));

Browser

// File
const file = document.querySelector('input[type="file"]').files[0];
client
  .uploadMedia({
    data: file,
  })
  .then((res) => console.log(res))
  .catch((err) => console.error(err));

// or URL
client
  .uploadMedia({
    data: 'https://example.com/image.png',
    // name: 'image.png', ← Optional
  })
  .then((res) => console.log(res))
  .catch((err) => console.error(err));

TypeScript

Parameter type for uploadMedia method

type UploadMediaRequest =
  | { data: File }
  | { data: Blob; name: string }
  | { data: ReadableStream; name: string; type: `image/${string}` }
  | {
      data: URL | string;
      name?: string | null | undefined;
      customRequestHeaders?: HeadersInit;
    };
function uploadMedia(params: UploadMediaRequest): Promise<{ url: string }>;

Tips

Separate API keys for read and write

const readClient = createClient({
  serviceDomain: 'serviceDomain',
  apiKey: 'readApiKey',
});
const writeClient = createClient({
  serviceDomain: 'serviceDomain',
  apiKey: 'writeApiKey',
});

LICENSE

Apache-2.0