commodo-fields-object

1.0.6 • Public • Published

commodo-fields-object

Build Status Covergrowth Status code style: prettier All Contributors PRs Welcome

A simple object field, used with the Commodo withFields higher order function.

Install

npm install --save commodo-fields-object

Or if you prefer yarn:

yarn add commodo-fields-object

Quick Example:

import { compose } from "ramda";
import { withFields, string } from "@commodo/fields";
import { object } from "commodo-fields-object";
 
const Page = compose(
  withFields({
    title: string(),
    content: object(), // Use it to store a single object.
    previousContent: object({ list: true }) // Or use it to store a list of objects.
    // Other fields you might need...
  }),
  // Other higher order functions (HOFs) you might need...
)();
 
const page = new Page();
company.name = "Welcome!";
 
// The object field can only accepts objects (with any structure). 
company.content = {
  elements: [
    {
      type: "xyz",
      text: "Lorem ipsum ...",
      elements: [{ type: "image", src: "https://..." }]
    }
  ]
};
 
company.previousContent = [
  { elements: [ ... ] },
  { elements: [ ... ] },
  { elements: [ ... ] }
];
 
// The following will throw the WithFieldsError error.
company.content = "A string...";
company.previousContent = [
  { elements: [ ... ] },
  "A string...",
  { elements: [ ... ] }
];

Note: alternatively, you could've also used the populate method to assign the data:

const company = new Company();
company.populate = {
  name: "Welcome!",
  content: {
    elements: [
      {
        type: "xyz",
        text: "Lorem ipsum ...",
        elements: [{ type: "image", src: "https://..." }]
      }
    ]
  },
  previousContent: [
    { elements: [ ... ] },
    { elements: [ ... ] },
    { elements: [ ... ] }
  ]
};

When to use this field?

This field can be used when you don't have a fixed structure of the data that's going to be assigned to it. The above example shows a perfect situation where this is necessary. Note that, although the field does allow any size of the object to be assigned, it's up to you to establish proper data validation and keep your code safe.

And finally, have in mind that, if it turns out that the data that's going to be assigned to the field, actually has a fixed structure, it's always best to use the fields field.

Contributors

Thanks goes to these wonderful people (emoji key):


Adrian Smijulj

💻 📖 💡 👀 ⚠️

This project follows the all-contributors specification. Contributions of any kind welcome!

Readme

Keywords

Package Sidebar

Install

npm i commodo-fields-object

Weekly Downloads

506

Version

1.0.6

License

MIT

Unpacked Size

18 kB

Total Files

21

Last publish

Collaborators

  • adrian1210