Creating Custom Commands with AdonisJs
In this blog, you should be able to find out how one can create custom ace commands in adonis.
So far, there are few already defined commands provided in adonis which can be found out using
adonis -- help
To create new commands you have to use
adonis make:command test
Once the command is created, you will be given instructions to add this command in start/app.js as follows
→ Open start/app.js→ Add App/Commands/Test to commands array
So the following needs to be updated your app.js file
const commands = ['App/Commands/Test']
Here, we will be updating a model called LeaveType using a json file ‘leave-types.yml’
#leave-types.yml{ "types": [ "Sick Leave (SL)", "Earned Leave (EL)", "Loss Of Pay (LOP)", "Restricted Holiday (RH)", "Other" ]}
Now to update the required action to be performed from your command, you need to override the handle method of Commands/Test.js as follows
# add this to the beginning of your command fileconst { Command } = require('@adonisjs/ace')const LeaveType = use('LeaveType') // used an alias for Model LeaveTypeconst Database = use('Database')const yaml = require('js-yaml');const fs = require('fs');
Update the handle action as follows –
async handle () { const fs = require('fs') const data = yaml.safeLoad(fs.readFileSync('./config/leave-types.yml', 'utf8')) data.types.forEach(function(type){ try { const leaveType = new LeaveType() leaveType.name = type await leaveType.save(); } catch (e){ console.log(e); } Database.close(); }}
To execute the command just run the signature present in the command file with adonis as –
adonis test
Happy Coding 🙂
In Case of queries, please feel free to drop a comment.