当类导出为单例时如何在另一个方法中调用方法

时间:2019-09-21 21:11:07

标签: javascript node.js singleton

我有两个方法的类。

我在另一个方法中调用一个方法,但得到TypeError: Cannot read property 'validateUrlInput' of undefined

该类作为单例导出;即在导出之前调用它。

Controller / API代码调用服务层代码,然后再调用数据访问层代码。

在服务层中,输入验证已导入,然后在类方法中使用。该类方法由Shortcut方法调用,这就是我得到错误的地方。

服务代码

const validatePublicUrlInput = require('../../validation/url/validatePublicUrlInput')
const PublicUrlModel = require('../core/publicUrl')

class PublicUrlService {
    shorten(req, res) {
        console.log('Service called')
        const { errors, isValid } = this.validateUrlInput(req.body)

        // Check validation
        if (!isValid) {
            return res.status(401).json(errors)
        }

        const { longUrl } = req.body
        const baseUrl = require('../../config/keys').baseURL

        PublicUrlModel.generateShortenedUrl(baseUrl, longUrl)
            .then(publicUrl => res.status(200).json(publicUrl))
            .then(err => res.status(400).json(err))

    }

    validateUrlInput(requestBody) {
        return validatePublicUrlInput(requestBody)
    }
}

module.exports = new PublicUrlService()

控制器/ API代码

const publicUrlService = require('../service/publicUrl')

class PublicUrl {
    constructor(router) {
        this.router = require('express').Router()
        this.shorten()
    }

    getRouter() {
        return this.router
    }

    // @route   POST api/url/shorten
    // @desc    Create short url route
    // @access  Public
    shorten() {
        this.router.post('/shorten', publicUrlService.shorten)
    }
}


module.exports = new PublicUrl()

输入验证码

const Validator = require('validator')
const isEmpty = require('../common/isEmpty.js')

module.exports = validatePublicUrlInput = data => {
    let errors = {}

    data.longUrl = !isEmpty(data.longUrl) ? data.longUrl : ''

    if (!Validator.isURL(data.longUrl, { min: 2, max: 30 })) {
        errors.longUrl = 'Invalid URL'
    }

    return {
        errors,
        isValid: isEmpty(errors)
    }
} 

0 个答案:

没有答案
相关问题