Best practice for constants messages in adonis js

I have created a constatnts.js in config directory. in which I am storing messages, which are to be displayed in api like this; What is the best way of managing these messages at single place and just provide key to fetch message for specific reason


//constants.js
'use strict'

async function success(type) {
    let response = ''
    switch (type) {
        case 'account_created':
            response = 'Account has been successfully created'
            break
        case 'login':
            response = 'User Successfully login'
            break
        default:
            response = 'Success'
    }
    return response
}

async function error(type) {
    let response = ''
    switch (type) {
        case 'general':
            response = 'An error has occurred, please try again.'
            break
        case 'login':
            response = 'Login failed. Invalid credentils'
            break
       case 'invalid_api_key':
            response = 'Api Key is invalid'
            break
        default:
            response = 'An error has occurred, please try again.'
    }
    return response
}
//Controller
 if(APP_KEY !== decrypted){
                let resp = await error(await constants.error('invalid_api_key'));
                return response.json(resp);
            }
1 Like

You can have them in config like you do.

Or put them into custom provider, something like ErrorMessageProvider

Or put them in error class and extend other errors based on this error class. This is lil harder to implement and might not fit into your project structure.

Personally I think provider would be the cleanest solution