@thadjbullet/sequelize-serialize

1.0.6 • Public • Published

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.

/@thadjbullet/sequelize-serialize/

    Package Sidebar

    Install

    npm i @thadjbullet/sequelize-serialize

    Weekly Downloads

    8

    Version

    1.0.6

    License

    MIT

    Unpacked Size

    9.9 kB

    Total Files

    7

    Last publish

    Collaborators

    • thadjbullet