DEV Community

Cover image for Building an Object Schema Validator From Scratch
Kinanee Samson
Kinanee Samson

Posted on

Building an Object Schema Validator From Scratch

Quite recently i took some time to build a Object schema validator, this was a direct result of working with MongoDB and mongoose. I thought about how the Schema validator worked in mongoose and what else is better than reinventing the wheel? If you've worked with mongoose and MongoDB you will understand what I'm talking about. This is not meant to replace the real deal, however I undertook this ordeal to get a better understanding of how the schema validator works under the hood and to deepen our problem solving skills.

When we are working with mongoose we will define an schema, this schema will validate the objects we try to add to the collection we attach the schema to, a typical example of a mongoose schema will look like below;

import { Schema } from 'mongoose'

const UserSchema = new Schema({
  name: {
     type: String,
  },
  age: {
     type: Number
  },
  hobbies: {
    type: Array
  }
});
Enter fullscreen mode Exit fullscreen mode

We then use this schema to create a model, whenever we try to add a new document to the collection, the schema will ensure that we define the right properties with the right values. Okay, we are going to be building our implementation with typescript. First we will define the types.

export  interface  ISchema {
    [Key: string]: schemaProp
}

type  schemaProp = {
    type: schmeValueType
    required?: [boolean, string]
    default?: schmeValueType
    minLength?: [number, string]
    maxLength?: [number, string]
    min?: [number, string]
    max?: [number, string]
    validate?: [(v: string) =>  boolean, string];
}

type  schmeValueType = String | Number | Boolean | Object | Array<any> | null;
Enter fullscreen mode Exit fullscreen mode

We used a dictionary type to type the property key on the schema, this is because we cannot explicitly tell the property key, but for sure we know that it will be a string. We expect every key on the schema to follow the schemaProp type. On the SchemaProp type, we define some properites that will determine how we will validate each field on the object. The only required property is the type, which equals to the constructor of some basic types provided by TypeScript, let's create a schema class;

Continue To Netcreed read more about this and more articles like this

Top comments (0)