Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Model typechecking not working as expected #57

Open
MycroftHolmes1989 opened this issue Jun 10, 2020 · 0 comments
Open

Model typechecking not working as expected #57

MycroftHolmes1989 opened this issue Jun 10, 2020 · 0 comments

Comments

@MycroftHolmes1989
Copy link

MycroftHolmes1989 commented Jun 10, 2020

The code:
The main file:
server.ts

import * as Fastify from "fastify";
import * as Dotenv from "dotenv";
import * as mongoose from "mongoose";
import routes from "./routes";
import fastify = require("fastify");

Dotenv.config();

const server = Fastify({ logger: true });

server.register(routes);

const connectToMongo = async (): Promise<void> => {
  try {
    await mongoose.connect(String(process.env.MONGODB_URI), {
      useNewUrlParser: true,
      useUnifiedTopology: true,
      useCreateIndex: true,
    });
  } catch (err) {
    throw err;
  }
};

const startServer = async (): Promise<void> => {
  try {
    await server.listen(Number(process.env.PORT), process.env.ADDR);
    server.log.info(`Started Server @ ${process.env.ADDR}:${process.env.PORT}`);
    await connectToMongo();
    server.log.info("Connected to Mongo...");
  } catch (err) {
    server.log.error(err);
    process.exit(-1);
  }
};

startServer();

A sample schema:
schema/task.ts

import { createSchema, Type, typedModel } from "ts-mongoose";

const taskSchema = createSchema(
  {
    entryDate: Type.date({ required: true }),
    particulars: Type.string({ required: true }),
    finishDate: Type.date({ required: false }),
  },
  { collection: "Task", timestamps: true }
);

export default taskSchema;

Models:
models.ts

import { typedModel } from "ts-mongoose";
import aggregateSchema from "./schemata/aggregate";
import taskSchema from "./schemata/task";
import transactionSchema from "./schemata/transaction";

const models = {
  Aggregate: typedModel("Aggregate", aggregateSchema),
  Task: typedModel("Task", taskSchema),
  Transaction: typedModel("Transaction", transactionSchema),
};

export default models;

Routes file (WIP):
route.ts

import * as Fastify from "fastify";
import { Server, IncomingMessage, ServerResponse } from "http";
import handlers from "./handlers";

const routes = (
  server: Fastify.FastifyInstance<Server, IncomingMessage, ServerResponse>,
  opts: Fastify.RegisterOptions<Server, IncomingMessage, ServerResponse>,
  done: (err?: Fastify.FastifyError | undefined) => void
): void => {
  server.get("/transaction", opts, handlers.getTransactionHandler);

  server.post("/transaction", opts, async (req, res) => {});

  server.get("/aggregate", opts, async () => {});

  server.get("/task", opts, async () => {});
  server.post("/task", opts, async () => {});
  server.put("/task/:id", opts, async () => {});

  done();
};

export default routes;

Handlers file (WIP):
handlers.ts

import { FastifyRequest, FastifyReply } from "fastify";
import { ServerResponse } from "http";

import models from "./models";
const { Aggregate, Task, Transaction } = models;

const handlers = {
  getTransactionHandler: async (
    req: FastifyRequest,
    _: FastifyReply<ServerResponse>
  ) => {
    const x = new Task({ entryDate: Date() });
    await x.save();
    return "Hello";
  },
};

export default handlers;

In handlers.ts, when I instantiate a Task object without one of the required properties, no error is thrown at compile time. Error is thrown at runtime. Also, intellisense of VS Code does not work with the property names. Is that expected behaviour? I expected class-like autocomplete behaviour. Is it possible to add a constructor to instantiate new objects of type Task, in my case?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant