Skip to content

Commit 8b71ff7

Browse files
committed
Generate controller in cli
1 parent 9b84db6 commit 8b71ff7

5 files changed

Lines changed: 66 additions & 0 deletions

File tree

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
],
1313
"scripts": {
1414
"start": "tsc && node ./bin/recife-cli project my-project-name",
15+
"cli": "tsc && node ./bin/recife-cli",
1516
"build": "tsc -p ."
1617
},
1718
"bin": {
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import fs from 'fs';
2+
import path from 'path';
3+
import commander from 'commander';
4+
import capitalize from '../utils/capitalize';
5+
import replaceMask from '../utils/replaceMask';
6+
7+
let controllerName: string = '';
8+
9+
commander
10+
.name(`recife-cli controller`)
11+
.arguments('<controller-name>')
12+
.action(name => (controllerName = name))
13+
.allowUnknownOption(false)
14+
.parse(process.argv);
15+
16+
if (controllerName) {
17+
controllerName = capitalize(
18+
controllerName.replace(/Controller|\.ts|\.js/g, '')
19+
);
20+
21+
controllerName += 'Controller';
22+
23+
const source = path.join(__dirname, '/../../templates/controller/template');
24+
const target = path.join(
25+
process.cwd(),
26+
'src/controllers',
27+
`${controllerName}.ts`
28+
);
29+
30+
try {
31+
const contentFile = fs.readFileSync(source).toString();
32+
fs.writeFileSync(
33+
target,
34+
replaceMask(contentFile, { name: controllerName })
35+
);
36+
} catch (err) {
37+
console.log(`\x1b[31m${err}\x1b[0m`);
38+
}
39+
} else {
40+
console.error('\x1b[31mSpecify the name controller.', '\x1b[0m');
41+
console.log(` For example: recife-cli controller UserController`);
42+
console.log(` Run recife-cli --help for more information\n`);
43+
}

src/utils/capitalize.ts

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
const capitalize = (string: string) => {
2+
return string.charAt(0).toUpperCase() + string.slice(1);
3+
};
4+
5+
export default capitalize;

src/utils/replaceMask.ts

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
const replaceMask = (content: string, values: any): string => {
2+
Object.keys(values).map(key => {
3+
content = content.split(`[[${key}]]`).join(values[key]);
4+
});
5+
return content;
6+
};
7+
8+
export default replaceMask;

templates/controller/template

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import { Query, Mutation } from 'recife';
2+
3+
class [[name]] {
4+
constructor() {
5+
//
6+
}
7+
}
8+
9+
export default [[name]];

0 commit comments

Comments
 (0)