I have a class with two methods.
I call a method in the other method but I get TypeError: Cannot read property 'validateUrlInput' of undefined
The class is exported as a singleton; that is invoking it before exporting.
The Controller/API code calls the service layer code which then calls the data access layer code.
In the service layer, the input validation is imported and then used in a class method. this class method is called by the shorten method and that is where I get the error.
SERVICE CODE
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()
CONTROLLER / API CODE
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()
INPUT VALIDATION CODE
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)
}
}