Repository
https://github.com/creatrixity/adonis-auth-scaffold
Pull Request
https://github.com/creatrixity/adonis-auth-scaffold/pull/6
Continuing with the development of the authentications scaffold for Adonis, this feature adds greater flexibility alongside a much more flexible means of getting solid, tested authentications system out of the box for your Adonis project.
Correspondence from adonis-auth-scaffold
viewers indicated that a lot of correspondents have API clients as primary use cases for their Adonis apps and were not invested in the current feature stack. Crafting a custom solution for API client consumers while maintaining interchangeability with current implementations already in production was important.
To strike a proper balance, it was important to be able to properly customize the use case for the CLI generator. Solving this problem involved using the graciously provided Adonis Ace helpers. The code below helps with ensuring a prompt is provided if the user does not supply either the --api-only
or --http-only
required flags.
async handle({}, {
apiOnly,
httpOnly
}) {
let client;
if (!apiOnly && !httpOnly) {
client = await this
.choice('Will this be used for a REST Api or for a HTTP Client?', [
{
name: 'For REST Api',
value: 'api'
}, {
name: 'For HTTP',
value: 'http'
}
])
} else {
client = apiOnly ? 'api': 'http';
}
// Rest of method...
}
To improve the user experience for the package, it is important to keep user effort to a minimum. To this end, it was important to provide a way of writing code to already existing Adonis files. The code below adds a new line of code after the first line of start/routes.js
// Write a module require statement to the routes.js file.
let routesFilePath = path.join(Helpers.appRoot(), 'start/routes.js');
let generatedRoutesFilename = apiOnly ? 'apiAuthRoutes.js': 'authRoutes.js';
await this._prependLineToFile({
filename: routesFilePath,
lineNumber: 2,
lineContent: `require('./${generatedRoutesFilename}');`
})
The prependLineToFile
method is defined below. This method takes a fully qualified filename (file path and name), a line number to have the new code inserted and the content to be inserted.
/**
* Prepends a line of text to a provided file.
*
* @param {String} Object.filename - Fully qualified path of the file to be operated on.
* @param {Number} Object.lineNumber - Line to operate on.
* @param {String} Object.lineContent - Content to be prepended.
*
* @return {Void}
*/
async _prependLineToFile ({
filename,
lineNumber,
lineContent
}) {
let fileContents = await this.readFile(filename, 'utf-8');
fileContents = fileContents.split("\n");
if (fileContents[lineNumber] === lineContent) return;
fileContents.splice(lineNumber, 0, `\n${lineContent}\n`)
await this.writeFile(filename, fileContents.join('\n'));
}
What's next?
- Provide further code documentation for existing code.
- Write improved documentation on current features.