1

I'm transforming my code from javascript to typescript, but struggeling with this issue, when trying to add data to the request, which obviously is not possible in typescript. The book, read from MongoDb and added to the request, is used in .get() and .delete() methods.

// bookModel.js
var mongoose = require('mongoose');

var bookModel =  mongoose.Schema({
    title: String,
    author: String,
    genre: String,
    read:{type:Boolean, default:false}
});
module.exports = mongoose.model('Book', bookModel, 'Book');
// bookController.js
var Book = require('./../models/bookModel'),
module.exports = function(){
var router = express.Router();

router.route('/:bookId')
        .all(function(req,res,next){
            Book.findById(req.params.bookId,function(err,book){
                if(err)
                    res.status(500).send(err);
                else if(book)
                {
                    req.book = book;
                    next();    
                }
                else
                {
                    res.status(404).send('No book found');
                }
            })
        })
        .get(function(req,res){
            res.json(req.book);
        })
        .delete(function(req,res){
            req.book.remove(function(err,book){
                if(err)
                    res.status(500).send(err);
                else
                    res.sendStatus(200);
            })
        })

How can data be added to the request in typescript and how can I retrieve the book in the following methods?

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
KVerwold
  • 261
  • 2
  • 9
  • You should be able to declare the types for req and res by using `function(req:express.Request, res:express.Response){}` – Tyler Kirby May 26 '17 at 13:29
  • In my TS .all() function, I'm using the types from express as `public all(req:Requst ,res: Response ,next: NextFunction){ ... }` but you cannot just add data to the request like `req.book = book`, as I can do in JS. Is there any other way, to pass data on the request to the methods get() and delete() ? – KVerwold May 27 '17 at 17:59
  • Possible duplicate of [Extend Express Request object using Typescript](https://stackoverflow.com/questions/37377731/extend-express-request-object-using-typescript) – Tyler Kirby May 30 '17 at 12:12

1 Answers1

2

In Typescript you can define types. You could mimic the JS object behavior by defining a type that has keys that are strings, and values that can be anything this way:

type Indexed = {
  [key: string]: any;
};

Now you could have a function definition that looks like this:

router.route('/:bookId')
        .all(function(req: Indexed, res, next) {

It's generally useful to be explicit about your intentions, which is not very well reflected at this moment.

req.book = book; // works
Menzies
  • 112
  • 1
  • 5