New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

microcms-js-sdk

Package Overview
Dependencies
Maintainers
4
Versions
30
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

microcms-js-sdk

JavaScript SDK Client for microCMS.

  • 3.0.0
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
14K
decreased by-27.94%
Maintainers
4
Weekly downloads
 
Created
Source

microCMS JavaScript SDK

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

Discord

Getting Started

Install

Install npm package.

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

$ npm install microcms-js-sdk

or

$ yarn add microcms-js-sdk

CDN support.

<script src="https://unpkg.com/microcms-js-sdk@latest/dist/umd/microcms-js-sdk.js"></script>

How to use

First, create a client.

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

// 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.
});

When using with a browser.

<script>
const { createClient } = microcms;

// 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.
});
</script>

After, How to use get it below.

client
  .get({
    endpoint: 'endpoint',
    queries: { limit: 20, filters: 'createdAt[greater_than]2021' },
  })
  .then((res) => console.log(res))
  .catch((err) => console.error(err));

client
  .get({
    endpoint: 'endpoint',
    contentId: 'contentId',
    queries: { fields: 'title,publishedAt' },
  })
  .then((res) => console.log(res))
  .catch((err) => console.error(err));

And, Api corresponding to each content are also available. example.

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

// Get list API detail data
client
  .getListDetail({
    endpoint: 'endpoint',
    contentId: 'contentId',
  })
  .then((res) => console.log(res))
  .catch((err) => console.error(err));

// Get object API data
client
  .getObject({
    endpoint: 'endpoint',
  })
  .then((res) => console.log(res))
  .catch((err) => console.error(err));
Get all content ids

This function can be used to retrieve all content IDs only.
Since filters and draftKey can also be specified, it is possible to retrieve only the content IDs for a specific category, or to include content from a specific draft.
The alternateField property can also 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',
  })
  .then((res) => console.log(res))
  .catch((err) => console.error(err));

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

// Get all content ids with draftKey
client
  .getAllContentIds({
    endpoint: 'endpoint',
    draftKey: 'draftKey',
  })
  .then((res) => console.log(res))
  .catch((err) => console.error(err));

// Get all content ids with alternateField
client
  .getAllContentIds({
    endpoint: 'endpoint',
    alternateField: 'url',
  })
  .then((res) => console.log(res))
  .catch((err) => console.error(err));
Get all contents

This function can be used to retrieve all content data.

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

// with queries
client
  .getAllContents({
    endpoint: 'endpoint',
    queries: { filters: 'createdAt[greater_than]2021', orders: '-createdAt' },
  })
  .then((res) => console.log(res))
  .catch((err) => console.error(err));
CREATE API

The following is how to use the write system when making a request to the write system API.

// Create 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
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
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
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 API

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

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

DELETE API

// Delete content
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.

// Type definition
type Content = {
  text: string,
}

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

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

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

The type of getAllContentIds is as follows.

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

Write functions can also be performed type-safely.

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

client.create<Content>({
  endpoint: 'endpoint',
  // Since `content` will be of type `Content`, no required fields will be missed.
  content: {
    title: 'title',
    body: 'body',
  },
})

client.update<Content>({
  endpoint: 'endpoint',
  // The `content` will be of type `Partial<Content>`, so you can enter only the items needed for the update.
  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)

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

Keywords

FAQs

Package last updated on 13 Mar 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc