Skip to content
This repository was archived by the owner on Apr 4, 2023. It is now read-only.

OsomePteLtd/sequelize-serialize

This branch is 29 commits ahead of, 3 commits behind Ajaxy/sequelize-serialize:master.

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Mar 27, 2023
3048fbb · Mar 27, 2023

History

64 Commits
Feb 27, 2023
Mar 26, 2023
Mar 26, 2023
Sep 20, 2018
Feb 22, 2023
Feb 23, 2023
Jan 14, 2019
Sep 20, 2018
Mar 27, 2023
Mar 27, 2023

Repository files navigation

sequelize-serialize

NPM version

The way to serialize Sequelize models using JSON Schema. Supports complex resources and associated models.

Example

Let’s say we need to return all users with posts in the blog, including the comments to these posts:

router.get('/blog/users', async (ctx) => {
  const users = await User.findAll({
    include: [{
      model: Post,
      required: true,
      include: [Comment]
    }]
  });

  ctx.body = serialize(users, schemas.UserWithPosts);
});

We can describe JSON fields for that with following schemas:

Expand to check them here
{
  "UserWithPosts": {
    "type": "object",
    "properties": {
      "name": {
        "type": "string"
      },
      "isAdmin": {
        "type": "boolean"
      },
      "age": {
        "type": "integer"
      },
      "posts": {
        "type": "array",
        "items": {
          "$ref": "#/definitions/Post"
        }
      }
    },
    "required": [
      "name",
      "isAdmin",
      "posts"
    ]
  },

  "User": {
    "type": "object",
    "properties": {
      "name": {
        "type": "string"
      },
      "isAdmin": {
        "type": "boolean"
      },
      "age": {
        "type": "integer"
      }
    },
    "required": [
      "name",
      "isAdmin"
    ]
  },

  "Post": {
    "type": "object",
    "properties": {
      "topic": {
        "type": "string"
      },
      "message": {
        "type": "string"
      },
      "comments": {
        "type": "array",
        "items": {
          "$ref": "#/definitions/Comment"
        }
      }
    },
    "required": [
      "topic",
      "message"
    ]
  },

  "Comment": {
    "type": "object",
    "properties": {
      "authorId": {
        "type": "integer"
      },
      "message": {
        "type": "string"
      }
    },
    "required": [
      "authorId",
      "message"
    ]
  },

Nulls

Supports null if schema is either:

type: ['..', 'null']

or

anyOf: [
  { type: '..' },
  { type: 'null' }
]

See also

Check out tinsypec for more smart JSON schema use cases.

About

Automatic JSON serialization of Sequelize models and collections based on JSON Schema

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript 100.0%