Skip to content

Commit

Permalink
Create new command for the react template
Browse files Browse the repository at this point in the history
  • Loading branch information
AayushSaini101 committed Jul 1, 2024
1 parent e559afb commit 22d5325
Show file tree
Hide file tree
Showing 6 changed files with 164 additions and 0 deletions.
12 changes: 12 additions & 0 deletions assets/create-template/templates/default/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"name": "myTemplate",
"generator": {
"renderer": "react",
"supportedProtocols": [
"mqtt"
]
},
"dependencies": {
"@asyncapi/generator-react-sdk": "^0.2.25"
}
}
4 changes: 4 additions & 0 deletions assets/create-template/templates/default/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
### First install all the dependencies for template using below command:
npm install
### Run the template using for a specific asyncapi document
asyncapi generate fromTemplate <templateName> ../asyncapi-template
10 changes: 10 additions & 0 deletions assets/create-template/templates/default/template/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { File, Text } from '@asyncapi/generator-react-sdk';

export default function ({ asyncapi, params, originalAsyncAPI }) {

Check failure on line 3 in assets/create-template/templates/default/template/index.js

View workflow job for this annotation

GitHub Actions / Test NodeJS PR - ubuntu-latest

'params' is defined but never used

Check failure on line 3 in assets/create-template/templates/default/template/index.js

View workflow job for this annotation

GitHub Actions / Test NodeJS PR - ubuntu-latest

'originalAsyncAPI' is defined but never used
return (
<File name="asyncapi.md">
<Text>My application's markdown file.</Text>
<Text>App name: **{asyncapi.info().title()}**</Text>
</File>
);
}
21 changes: 21 additions & 0 deletions assets/create-template/templates/default/template/package.json.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@

import { File } from '@asyncapi/generator-react-sdk';
import fetch from 'node-fetch';
export default async function ({ asyncapi }) {
const description = asyncapi.info().description();
const packageName = '@asyncapi/generator-react-sdk';
const npmRegistryUrl = `https://registry.npmjs.org/${encodeURIComponent(packageName)}`;
const response = await fetch(npmRegistryUrl);
const data = await response.json();
const generatorSDKversion = data['dist-tags'].latest;
return (
<File name={'package.json'}>{`{
"name": "${asyncapi.info().title().toLowerCase().replace(/ /g, '-')}",
"version": "0.1.0",
"description": "${description ? asyncapi.info().description().split('\n')[0] : ''}",
"dependencies": {
"@asyncapi/generator-react-sdk": "^${generatorSDKversion}"
}
}`}</File>
);
}
90 changes: 90 additions & 0 deletions src/commands/new/template.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import { promises as fPromises } from 'fs';
import Command from '../../core/base';
import { resolve, join } from 'path';
import {load } from '../../core/models/SpecificationFile';
import fs from 'fs-extra';
import { templateFlags } from '../../core/flags/new/template.flags';
import { cyan, gray } from 'picocolors';

export const successMessage = (projectName: string) =>
`🎉 Your template is succesfully created
⏩ Next steps: follow the instructions ${cyan('below')} to manage your project:
cd ${projectName}\t\t ${gray('# Navigate to the project directory')}
npm install\t\t ${gray('# Install the project dependencies')}
asyncapi generate fromTemplate <templateName> ../${projectName} \t\t ${gray('# Execute the template from anasyncapi document')}
You can also open the project in your favourite editor and start tweaking it.
`;

const errorMessages = {
alreadyExists: (projectName: string) =>
`Unable to create the project because the directory "${cyan(projectName)}" already exists at "${process.cwd()}/${projectName}".
To specify a different name for the new project, please run the command below with a unique project name:
${gray('asyncapi new template --name ') + gray(projectName) + gray('-1')}`,
};

export default class template extends Command {
static description = 'Creates a new template';
protected commandName = 'template';
static readonly successMessage = successMessage;
static readonly errorMessages = errorMessages;
static flags = templateFlags();

async run() {
const { flags } = await this.parse(template); // NOSONA

const {
name: projectName,
template: templateName,
file,

Check failure on line 41 in src/commands/new/template.ts

View workflow job for this annotation

GitHub Actions / Test NodeJS PR - ubuntu-latest

'file' is assigned a value but never used
'force-write': forceWrite,

Check failure on line 42 in src/commands/new/template.ts

View workflow job for this annotation

GitHub Actions / Test NodeJS PR - ubuntu-latest

'forceWrite' is assigned a value but never used
} = flags;

const PROJECT_DIRECTORY = join(process.cwd(), projectName);

const templateDirectory = resolve(
__dirname,
'../../../assets/create-template/templates/',
templateName
);

{
try {
await fPromises.mkdir(PROJECT_DIRECTORY);
} catch (err: any) {
switch (err.code) {
case 'EEXIST':
this.error(errorMessages.alreadyExists(projectName));
break;
case 'EACCES':
this.error(
`Unable to create the project. We tried to access the "${PROJECT_DIRECTORY}" directory but it was not possible due to file access permissions. Please check the write permissions of your current working directory ("${process.cwd()}").`
);
break;
case 'EPERM':
this.error(
`Unable to create the project. We tried to create the "${PROJECT_DIRECTORY}" directory but the operation requires elevated privileges. Please check the privileges for your current user.`
);
break;
default:
this.error(
`Unable to create the project. Please check the following message for further info about the error:\n\n${err}`
);
}
}

try {
await fs.copy(templateDirectory, PROJECT_DIRECTORY);
this.log(successMessage(projectName));
} catch (err) {
this.error(
`Unable to create the project. Please check the following message for further info about the error:\n\n${err}`
);
}
this.specFile = await load(`${templateDirectory}/asyncapi.yml`);
this.metricsMetadata.template = flags.template;
}
}
}
27 changes: 27 additions & 0 deletions src/core/flags/new/template.flags.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { Flags } from '@oclif/core';

export const templateFlags = () => {
return {
help: Flags.help({ char: 'h' }),
name: Flags.string({
char: 'n',
description: 'Name of the Project',
default: 'project',
}),
template: Flags.string({
char: 't',
description: 'Name of the Template',
default: 'default',
}),
file: Flags.string({
char: 'f',
description:
'The path to the AsyncAPI file for generating a template.',
}),
'force-write': Flags.boolean({
default: false,
description:
'Force writing of the generated files to given directory even if it is a git repo with unstaged files or not empty dir (defaults to false)',
}),
};
};

0 comments on commit 22d5325

Please sign in to comment.