GithubHelp home page GithubHelp logo

buttercms / buttercms-js Goto Github PK

View Code? Open in Web Editor NEW
161.0 161.0 31.0 855 KB

Node/JS API client for ButterCMS (https://buttercms.com)

License: Other

JavaScript 90.80% HTML 9.20%
cms express-js hapi koa node node-cms nodejs nodejs-cms

buttercms-js's Introduction

ButterCMS JS client

npm version

Documentation

For a comprehensive list of examples, check out the API documentation.

ButterCMS-JS version 2 will be supported until January 2025. Version 3 is slated for launch in November 2024 when Node v20 is moved to maintenance mode.

Installation

Requires Node.js version 18 or greater.

npm install buttercms --save

Butter can also be included directly in HTML:

<script src="https://cdnjs.buttercms.com/buttercms-2.0.1.min.js"></script>

Native Fetch

ButterCMS-JS version 2 will be using the native fetch API. This means that the fetch API will be used to make requests to the ButterCMS API. This is a breaking change for anyone using version 1 of the ButterCMS-JS package.

Native fetch is built into Node v18 as well as all modern browsers. This lessens the need for third-party fetch libraries and achieves consistency between Node and browser environments.

Overview

Every resource is accessed via your butter instance:

Using ES6 or Typescript:

import Butter from "buttercms";
const butter = Butter("api_token_567abe");

Using CDN:

<script>
  const butter = Butter("api_token_567abe");
</script>

Every resource method returns a promise:

// Get blog posts
butter.post.list({page: 1, page_size: 10})
  .then(function(response) {
    console.log(response)
  })
  .catch(function(error) {
    console.error(error)
  })

If using async/await:

async function getPosts() {
  try {
    const response = await butter.post.list({page: 1, page_size: 10});
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}

Pages

Where you see params it is a plain js object, e.g. {page: 1}. For a list of params see the API documentation

  • page
    • retrieve(page_type, page_slug[, params])
    • list(page_type[, params])
    • search(query[, params])
    • cancelRequest()
// Get page
butter.page.retrieve("casestudy", "acme-co").then(function(resp) {
 console.log(resp)
});

If using async/await:

async function getPage() {
  try {
    const response = await butter.page.retrieve("casestudy", "acme-co");
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}

Collections

  • content
    • retrieve(collection[, params])
    • cancelRequest()
// Get FAQ
butter.content.retrieve("faq", {locale: "es"}).then(function(resp) {
  console.log(resp)
});

If using async/await:

async function getFAQ() {
  try {
    const response = await butter.content.retrieve("faq", {locale: "es"});
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}

Preview mode

Preview mode can be used to setup a staging website for previewing content fields or for testing content during local development. To fetch content from preview mode add an additional argument, true, to the package initialization:

const butter = Butter(
  "your butter API token", 
  { testMode: true }
);

Or use an environment variable:

const butter = Butter(
  "your butter API token", 
  { testMode:  process.env.BUTTER_PREVIEW_MODE }
);

Blog Engine

  • post
    • retrieve(slug[, params])
    • list([params])
    • search(query[, params])
    • cancelRequest()
  • category
    • retrieve(slug[, params])
    • list([params])
    • cancelRequest()
  • tag
    • retrieve(slug[, params])
    • list([params])
    • cancelRequest()
  • author
    • retrieve(slug[, params])
    • list([params])
    • cancelRequest()
  • feed
    • retrieve(type[, params])
    • cancelRequest()

See our node app for a full example.

Timeouts

The default timeout threshold is 3000ms but you can change it:

const butter = Butter(
  "your butter API token", 
  { timeout: 5000 }
);

Caching

The default cache is set to default:

const butter = Butter(
  "your butter API token", 
  { cache: "only-if-cached" }
);

Canceling a request

Each resource returns a cancelRequest method that can be used to cancel a request:

butter.post.cancelRequest();

This will cancel all pending requests for that resource type. It will catch the cancelation and return a rejected Promise for your .catch() method or be able to be caught in an async function via a try/catch block.

Hooks

If you need to custom headers, caching, automatic retry or any other specific functionality on the transport layer, you can hook up into our fetch hooks. The following hooks are available as Butter configuration options:

const butter = Butter(
  "your butter API token", 
  { 
    onError: Function,
    onRequest: Function,
    onResponse: Function
  }
);

onRequest - called prior to making a request to the API. This can be declared as an async function to allow for async operations to be performed before the request is made.

onRequest(resource, config)

resource - The resource is the Butter API endpoint to be called config - This is the configuration object that will be used to make the request

config includes:

cancelRequest - A function that can be called to cancel the request in the hook headers - The headers that will be sent with the request. This is in the JS Headers API format. Users are able to modify these headers in the hook. options - Options are the original config options set when initializing the Butter instance. This includes the cache, testMode, timeout. Hook functions are not included in this object. params - The query parameters that will be sent with the request. Users are able to modify these parameters in the hook. type - The type of resource api that is being requested. This string helps the developer to differentiate what resource is being called in the global hook.

options, headers, and params are to be returned by the onRequest hook for further processing and request.

onResponse - called after a response is received from the API. This can be declared as an async function to allow for async operations to be performed after the response is received.

onResponse (response, config)

response - The response object that was received from the API. This is in the JS Fetch Response API format and is a clone of the original response object. This will allow the user to parse the response to get the data they need whether it be JSON, text, blob, etc. The original response will be returned as JSON to the resource function call's promise resolution.

config - This is the configuration object that was used to make the request

config includes:

options - Options are the original config options set when initializing the Butter instance. This includes the cache, testMode, timeout. Hook functions are not included in this object. params - The query parameters were sent with the request. type - The type of resource api that was requested. This string helps the developer to differentiate what resource was called in the global hook.

onResponse expects no return values.

onError - called when an error is received from the API. This is not considered an async function.

onError (errors, config)

errors - the errors returned from the API and/or the fetch request. Comes in the following object format:

{
    details: "Error details",
}

config includes:

options - Options are the original config options set when initializing the Butter instance. This includes the cache, testMode, timeout. Hook functions are not included in this object. params - The query parameters were sent with the request. type - The type of resource api that was requested. This string helps the developer to differentiate what resource was called in the global hook.

onError expects no return values.

Documentation

Documentation is available at https://buttercms.com/docs/api/node

Other

View NodeJS Blog engine and Full CMS for other examples of using ButterCMS with NodeJS.

buttercms-js's People

Contributors

amhunt avatar beautifulcoder avatar chasecoleman avatar courcelan avatar creyes-pcty avatar d-corler avatar dependabot[bot] avatar edwardnaylor avatar github-actions[bot] avatar jackdomleo7 avatar jakelumetta avatar jamesqquick avatar jkelin avatar marcinpece-apptension avatar martinalbert avatar orlyohreally avatar prokopsimek avatar rogerjin12 avatar violantecodes avatar zuzanawangle avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

buttercms-js's Issues

Required 1.0.16 with ability to setup timeout.

Hi, I've just started integration of buttercms on React, and I have specific case, when i must increase request time, but version 1.0.16 still not in production. So my question is when version 1.0.16 will be in production? (on npmjs?)

Pages list always returns an empty array

When calling: https://api.buttercms.com/v2/pages/*/?preview=1&auth_token=<api_key> according to the API doc it should return me an array with all available pages.
But the array is always empty even though we have data and using queuing it like this works:
https://api.buttercms.com/v2/pages/<page_type>/<page_key>/?auth_token=<api_key>

Changelog?

Is there a maintained changelog for this package anywhere, I can't seem to find one? It's important for developers to be aware of any changes in packages between versions

missing git tags

Please push your git tags. I see there's been a new patch version release of the package to npm, v1.2.10. It seems to break our integration, likely related to updating axios. I went back to v1.2.9 which works, but I can't find the according git tags for these releases here. So it's hard to investigate what caused the break.

Bug - axios.create is not a function

Getting an error in v1.2.10 of the package with axios

TypeError: axios.create is not a function (get, butter.js:53)

The project that I'm using this library in does not have a separate install of axios so when I'm trying to use 1.2.10 of buttercms-js, I get the error that axios.create is not a function.

The workaround is downgrading the library to v1.2.9. Below are the snippets from each version from package-lock.json for additional info.

    "buttercms": {
      "version": "1.2.9",
      "requires": {
        "axios": "~0.21.1"
      }
    },

    "buttercms": {
      "version": "1.2.10",
      "requires": {
        "axios": "^1.2.5"
      }
    },

TypeError wrapping returned promise to observable

Hi running into an issue with the latest version (1.2.2) typings.
In 1.1.4, I was able to wrap the Promise return in an observable from() for an Angular Injectable, but now I get the following:

image

This error occurs just after a successful returned API response. Rxjs maps the value from the service then errors just after the observable's completion.

After some experimenting, comparing 1.1.4 and 1.2.2, the only real difference I see are the type definitions significantly changed.

The client package is pretty handy, but this lies outside the scope of Angular's context.

Create npm release for lastest master

It appears that the axios vulnerability is still not patched for consumers of this npm module until someone publishes a [email protected].

image

Temporary Fix

Anyone looking for the secure version can run npm install "git://github.com/ButterCMS/buttercms-js#f85fa52"

Typescript build error in butter.d.ts

butter.d.ts is throwing an error when I try to build my project using typescript.

declare module "buttercms" {

  export = Butter;  <-- This line throwing error

}

Error: "Exports and export assignments are not permitted in module augmentations."

Pagination issue

I tried to implement fetch one-by-one blog posts and got an interesting issue with the page_size property of the butter.post.search options object. My call chain looks something like this:

import Butter from 'buttercms'

let fetchPageNumber = 0

const fetchBlog = () => {
  if (!fetchPageNumber) return 

  Butter(process.env.NEXT_PUBLIC_BUTTER_CMS_API_KEY)
    .post
    .search({ page: fetchPageNumber, page_size: 1 })
    .then(({ data }) => {
      console.log(data)
      fetchPageNumber = data.meta.next_page
    })
}

In data.meta.count I got 4 items, but when I reached the 3rd page it cast an error: Invalid page \"3\": That page contains no results.. When I changed page_size to 2, it works as expected, also if I passed something like a: 'a' into the search method to make it look like this: ... .search({ page: fetchPageNumber, page_size: 1, a: 'a' }), it started works as expected too 😅.

Main technology: Next v13

Potential security issue

Hey there!

I belong to an open source security research community, and a member (@harunoz) has found an issue, but doesn’t know the best way to disclose it.

If not a hassle, might you kindly add a SECURITY.md file with an email, or another contact method? GitHub recommends this best practice to ensure security issues are responsibly disclosed, and it would serve as a simple instruction for security researchers in the future.

Thank you for your consideration, and I look forward to hearing from you!

(cc @huntr-helper)

Type declaration file

Hi,

I would like to use buttercms with Typescript however there is no declaration file available neither here or on DefinitelyTyped.

Would you consider adding a declaration file to enable use with Typescript ? Or is there any workaround ?

Thanks.

edit: As a temporary workaround I created a dummy declaration file. You lose the autocomplete features but it's compatible with typescript.
declare module "buttercms";

my params are being converted

Hi,

im writting this:

butter.page.list('support_faq', ['&order=-date_published'])

but is being converted to this

GET https://api.buttercms.com/v2/pages/support_faq/?0=%26order%3D-date_published 401 (Unauthorized)

why not making optional params to object instead of arrays?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.