Sunday, 16 April 2017

Importing Objection Model in Typing for Express Middleware Node

so I want to re-code an "old" project in TypeScript 2, I'm using VS Code last version. This project uses Passport Express Middleware, so its Typing includes a express.Request.user of type "any" But, I use Objection as MySQL ORM so I have a Class of that user. Lets make it easier, instead of merge "user". Let's assume (I have tried it and failed) I want to have req.lastOrder on my middlewares of the type Order, so I have a class like this:

import { Model } from 'objection';

export default class OrderModel extends Model {
  readonly id_order;

  public static get tableName() {
    return 'orders';
  }

  constructor(){
    super();
  } 
}

Now, I have a Typing to merge this type in express.Request, in a file called "express.d.ts":

import OrderModel from '../models/Order';

declare module Express {
  export interface Request {
    lastOrder?: OrderModel;
  }
}

The "simplified" directory structure is like this:

\ src
-- \ models
---- Order.ts
-- \ typings
---- express.d.ts
-- app.js
tsconfig.json
\ node_modules

And the tsconfig has this config:

{
    "compilerOptions": {
      "module": "commonjs",
      "target": "es6",
      "baseUrl": "./",
      "noImplicitAny": false,
      "sourceMap": false,
      "typeRoots": [
        "node_modules/@types"
      ],
      "outDir": "out",
      "declaration": true,
      "traceResolution": true
    },
    "files": [
        "node_modules/objection/typings/objection/index.d.ts",
        "src/typings/express.d.ts"
    ],
    "include": [
        "src/**/*"
    ]
}

Now, if I want to make a req.lastOrder inside a Middleware, I don't have autocompletion or antyhing. After digging around I got that Importing the class inside de .d.ts, breaks the entire file... So I don't know how it works... I just can't make it work...

Do you have any suggestion? Thanks!



via yNeolh

No comments:

Post a Comment