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

Latest commit

 

History

History
133 lines (118 loc) · 2.27 KB

README.md

File metadata and controls

133 lines (118 loc) · 2.27 KB

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.