mgc 1.0.1 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bin/generate.js CHANGED
@@ -3,7 +3,7 @@
3
3
  import path from "path";
4
4
  import { program } from "commander";
5
5
 
6
- import { generateProject } from "../services/filecopy.service.js";
6
+ import { generateModule } from "../services/filecopy.service.js";
7
7
 
8
8
  program
9
9
  .command("gen <modulePath>")
@@ -18,7 +18,7 @@ program
18
18
 
19
19
  const currentDir = path.join(process.cwd(), externalPath || "");
20
20
 
21
- generateProject(modulePath, currentDir);
21
+ generateModule(modulePath, currentDir);
22
22
  });
23
23
 
24
24
  program.parse(process.argv);
@@ -11,11 +11,17 @@ AWS_SECRET_ACCESS_KEY=""
11
11
 
12
12
  ## Usae
13
13
 
14
+ ### Packages Requied
15
+
16
+ ```
17
+ yarn add nodemailer handlebars @aws-sdk/client-ses zod
18
+ ```
19
+
14
20
  - First you have to create a `.hbs` template in `/templates` directory with necessary placeholders i.e. `{{verificationCode}}` or any other name as per your requirement
15
- - Then in `email.interface.ts` file on `EmailTemplate` type, append the newly created file name, i.e. if you created `forgot-password.hbs`, the new type should be
21
+ - Then in `email.interface.ts` file on `EmailTemplate` type, append the newly created file name, i.e. if you created `forgot-password.hbs`, the new type should be
16
22
 
17
23
  ```ts
18
- export type EmailTemplate = "welcome" | "verify-email" | 'forgot-password';
24
+ export type EmailTemplate = "welcome" | "verify-email" | "forgot-password";
19
25
  ```
20
26
 
21
27
  - Now use `sendMail` function wherever you require
@@ -32,6 +38,7 @@ sendMail({
32
38
  ```
33
39
 
34
40
  ## Important Note
41
+
35
42
  - we have to copy hbs file as it won't happen during ts compilation step thus add this script on your `package.json`
36
43
 
37
44
  ```json
@@ -43,3 +50,8 @@ sendMail({
43
50
  ```json
44
51
  "build": "tsc && yarn copy-hbs",
45
52
  ```
53
+
54
+ ## Bugs
55
+
56
+ - [ ] Ts do not read .hbs file so, for now, we have copy hbs file using copy-hbs package when building and starting the application.
57
+ - [ ] need to generate dynamic date i.e. @2023 copyright
@@ -0,0 +1,24 @@
1
+ import "dotenv/config";
2
+
3
+ import { z } from "zod";
4
+
5
+ const envSchema = z.object({
6
+ BUCKET: z.string().optional(),
7
+ EMAIL_FROM: z.string().nonempty(),
8
+ AWS_REGION: z.string().nonempty(),
9
+ AWS_ACCESS_KEY_ID: z.string().nonempty(),
10
+ AWS_SECRET_ACCESS_KEY: z.string().nonempty(),
11
+ });
12
+
13
+ export const env = envSchema.parse(process.env);
14
+
15
+ export default {
16
+ aws: {
17
+ region: env.AWS_REGION,
18
+ accessKeyId: env.AWS_ACCESS_KEY_ID,
19
+ secretAccessKey: env.AWS_SECRET_ACCESS_KEY,
20
+ },
21
+ email: {
22
+ from: process.env.EMAIL_FROM,
23
+ },
24
+ };
@@ -4,14 +4,15 @@ import nodemailer from "nodemailer";
4
4
  import handlebars from "handlebars";
5
5
  import * as aws from "@aws-sdk/client-ses";
6
6
 
7
+ import config from "./email.config";
7
8
  import { MailerParams, EmailTemplate } from "./email.interface";
8
9
 
9
10
  const ses = new aws.SESClient({
10
11
  apiVersion: "2010-12-01",
11
- region: process.env.AWS_REGION,
12
+ region: config.aws.region,
12
13
  credentials: {
13
- accessKeyId: process.env.AWS_ACCESS_KEY_ID || "",
14
- secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY || "",
14
+ accessKeyId: config.aws.accessKeyId,
15
+ secretAccessKey: config.aws.secretAccessKey,
15
16
  },
16
17
  });
17
18
 
@@ -20,7 +21,7 @@ const nodeMailerTransporter = nodemailer.createTransport({
20
21
  });
21
22
 
22
23
  export function sendMail(emailData: MailerParams) {
23
- emailData.from = emailData.from || process.env.EMAIL_FROM;
24
+ emailData.from = emailData.from || config.email.from;
24
25
 
25
26
  // handlebars config
26
27
  if (emailData.template) {
@@ -0,0 +1,50 @@
1
+ # S3 Module
2
+
3
+ Generating signed url for uploading and previewing files
4
+
5
+ ## Required env variables
6
+
7
+ ```
8
+ BUCKET: '',
9
+ AWS_REGION: '',
10
+ AWS_ACCESS_KEY_ID: '',
11
+ AWS_SECRET_ACCESS_KEY: '',
12
+
13
+ ```
14
+
15
+ ## Usage
16
+
17
+ ### Packages Required
18
+
19
+ ```
20
+ yarn add http-status http-errors @aws-sdk/client-s3 @aws-sdk/s3-request-presigner zod dotenv
21
+ ```
22
+
23
+ ### Implementation
24
+
25
+ ```ts
26
+ // 1. signed url for previewing file
27
+ const key = "file-management/sample.pdf";
28
+ const fileName = "sample.pdf";
29
+ const downlaod = false as boolean;
30
+
31
+ const previewSignedUrl = await s3Service.generateSignedURL({
32
+ key: key,
33
+ fileName: fileName,
34
+ download: download,
35
+ });
36
+
37
+ // 2. generate a pre-signed url for uploading the file
38
+ const fileName = "sample.pdf";
39
+ const prefix = "file-management/";
40
+
41
+ const { signedUrl: preSignedUploadUrl, key } =
42
+ await s3Service.generatePresignedUrl({ prefix, fileName });
43
+
44
+ // Optionally for mime-types
45
+ import mime from "mime-types";
46
+ const mimeType = mime.lookup(fileName);
47
+
48
+ // 3. Delete file
49
+ await s3Service.deleteFile(file.key);
50
+ ```
@@ -0,0 +1,24 @@
1
+ import "dotenv/config";
2
+
3
+ import ms from "ms";
4
+ import { z } from "zod";
5
+
6
+ // validate environment variables to ensure they are available at runtime
7
+ const envSchema = z.object({
8
+ BUCKET: z.string().optional(),
9
+ AWS_REGION: z.string().nonempty(),
10
+ AWS_ACCESS_KEY_ID: z.string().nonempty(),
11
+ AWS_SECRET_ACCESS_KEY: z.string().nonempty(),
12
+ });
13
+
14
+ export const env = envSchema.parse(process.env);
15
+
16
+ export default {
17
+ aws: {
18
+ bucket: env.BUCKET,
19
+ region: env.AWS_REGION,
20
+ accessKeyId: env.AWS_ACCESS_KEY_ID,
21
+ secretAccessKey: env.AWS_SECRET_ACCESS_KEY,
22
+ uploadSignedUrlExpiresIn: ms("60m"), // since we are expecting large files, we are setting this to 60 minutes
23
+ },
24
+ };
@@ -0,0 +1,11 @@
1
+ import { S3Client } from '@aws-sdk/client-s3';
2
+
3
+ import config from './s3.config';
4
+
5
+ export const s3Client = new S3Client({
6
+ region: config.aws.region,
7
+ credentials: {
8
+ accessKeyId: config.aws.accessKeyId,
9
+ secretAccessKey: config.aws.secretAccessKey,
10
+ },
11
+ });
@@ -0,0 +1,103 @@
1
+ import httpStatus from "http-status";
2
+ import createError from "http-errors";
3
+ import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
4
+ import {
5
+ GetObjectCommand,
6
+ PutObjectCommand,
7
+ HeadObjectCommand,
8
+ DeleteObjectCommand,
9
+ } from "@aws-sdk/client-s3";
10
+
11
+ import config from "./s3.config";
12
+ import { s3Client } from "./s3.lib";
13
+ import { generateString, getMime } from "./S3.helper";
14
+
15
+ import { IGeneratePresignedUrl } from "./s3.interface";
16
+
17
+ export const msToSeconds = (ms: number) => ms / 1000;
18
+
19
+ /**
20
+ * Generates a signed URL for accessing an S3 object.
21
+ * @param {string} key - The file name stored in s3.
22
+ * @param {string} fileName - The file name stored in db.
23
+ * @returns {Promise<{key: string, signedUrl: string}>>} The signed URL.
24
+ */
25
+ export const generateSignedURL = async ({
26
+ key,
27
+ fileName,
28
+ download,
29
+ }: {
30
+ key: string;
31
+ fileName: string;
32
+ download: boolean;
33
+ }) => {
34
+ const getObjectParams = {
35
+ Bucket: config.aws.bucket,
36
+ Key: key,
37
+ ...(download
38
+ ? { ResponseContentDisposition: `attachment;filename=${fileName}` }
39
+ : {}), // use browser default download manager
40
+ };
41
+
42
+ const command = new GetObjectCommand(getObjectParams);
43
+ const signedUrl = await getSignedUrl(s3Client, command, { expiresIn: 120 });
44
+
45
+ return {
46
+ key,
47
+ signedUrl,
48
+ };
49
+ };
50
+
51
+ /**
52
+ * Generates a presigned URL for uploading a file to an S3 bucket.
53
+ * @param {object} params - The parameters for generating the presigned URL.
54
+ * @param {string} params.bucket - The S3 bucket name.
55
+ * @param {string} params.fileName - The desired file name.
56
+ * @returns {Promise<{key: string, signedUrl: string}>} The presigned URL.
57
+ */
58
+ export const generatePresignedUrl = async ({
59
+ prefix = "",
60
+ bucket,
61
+ fileName,
62
+ }: IGeneratePresignedUrl) => {
63
+ const mime = getMime(fileName);
64
+
65
+ const key = prefix + `${await generateString(10)}_${Date.now()}.` + mime;
66
+
67
+ const command = new PutObjectCommand({
68
+ Bucket: bucket || config.aws.bucket,
69
+ Key: key,
70
+ });
71
+ const signedUrl = await getSignedUrl(s3Client, command, {
72
+ expiresIn: msToSeconds(config.aws.uploadSignedUrlExpiresIn),
73
+ });
74
+ return {
75
+ key,
76
+ signedUrl,
77
+ };
78
+ };
79
+
80
+ export const getFileSize = async (key: string): Promise<number> => {
81
+ const getObjectMetaDataParams = {
82
+ Bucket: config.aws.bucket,
83
+ Key: key,
84
+ };
85
+
86
+ const response = await s3Client.send(
87
+ new HeadObjectCommand(getObjectMetaDataParams)
88
+ );
89
+ const sizeInBytes = response.ContentLength;
90
+
91
+ if (!sizeInBytes) throw createError(httpStatus.NOT_FOUND, "File not found");
92
+
93
+ return sizeInBytes;
94
+ };
95
+
96
+ export const deleteFile = (key: string) => {
97
+ const deleteObjectParams = {
98
+ Bucket: config.aws.bucket,
99
+ Key: key,
100
+ };
101
+
102
+ return s3Client.send(new DeleteObjectCommand(deleteObjectParams));
103
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mgc",
3
- "version": "1.0.1",
3
+ "version": "1.2.0",
4
4
  "description": "A cli based tool for generating your saved modules",
5
5
  "author": "Admond Tamang",
6
6
  "license": "MIT",
@@ -8,6 +8,10 @@
8
8
  "bin": {
9
9
  "cli": "bin/generate.js"
10
10
  },
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "git@github.com:admondtamang/module-generate-cli.git"
14
+ },
11
15
  "publishConfig": {
12
16
  "access": "public"
13
17
  },
package/readme.md CHANGED
@@ -7,10 +7,10 @@ Module Generate Cli (mgc)
7
7
  To generate a module
8
8
 
9
9
  ```
10
- mgc gen express/email
10
+ npx mgc gen express/email
11
11
  ```
12
12
 
13
13
  ## Inspiration
14
14
 
15
- https://github.com/arminbro/generate-react-cli#openai-integration-alpha-release
16
- https://github.com/shadcn-ui
15
+ - https://github.com/arminbro/generate-react-cli#openai-integration-alpha-release
16
+ - https://github.com/shadcn-ui
@@ -39,13 +39,13 @@ export const getCurrentFolder = (name) => {
39
39
  else return name;
40
40
  };
41
41
 
42
- export const generateProject = (modulePath, toGeneratePath) => {
42
+ export const generateModule = (modulePath, toGeneratePath) => {
43
43
  // to get __dirname
44
44
  const __filename = fileURLToPath(import.meta.url);
45
45
  const __dirname = path.dirname(__filename);
46
46
 
47
47
  // copy template files and folders
48
- const templatePath = path.join(__dirname, "../templates/" + modulePath);
48
+ const templatePath = path.join(__dirname, "../modules/" + modulePath);
49
49
 
50
50
  // generate module folder
51
51
  const moduleName = getCurrentFolder(modulePath);
@@ -58,5 +58,5 @@ export const generateProject = (modulePath, toGeneratePath) => {
58
58
  // copy module to your dir
59
59
  copyFolderSync(templatePath, newPathToGenerate);
60
60
 
61
- console.log("Module generated successfully!");
61
+ console.log("Yeah!!! Module generated successfully!");
62
62
  };
@@ -1,121 +0,0 @@
1
- import fs from 'fs';
2
- import httpStatus from 'http-status';
3
- import createError from 'http-errors';
4
- import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
5
- import { GetObjectCommand, PutObjectCommand, HeadObjectCommand, DeleteObjectCommand } from '@aws-sdk/client-s3';
6
-
7
- import { config } from '../../../config';
8
- import { s3Client } from '../../../lib/aws';
9
- import { generateString, getMime } from './S3.helper';
10
- import { msToSeconds } from '../../../utils/msToSeconds';
11
-
12
- import { IFileUploadResult, IGeneratePresignedUrl, IPutFilesOptions } from './s3.interface';
13
-
14
- /**
15
- * Generates a signed URL for accessing an S3 object.
16
- * @param {string} key - The file name stored in s3.
17
- * @returns {Promise<{key: string, signedUrl: string}>>} The signed URL.
18
- */
19
- export const generateSignedURL = async (key: string) => {
20
- const getObjectParams = {
21
- Bucket: config.aws.bucket,
22
- Key: key,
23
- };
24
-
25
- const command = new GetObjectCommand(getObjectParams);
26
- const signedUrl = await getSignedUrl(s3Client, command, { expiresIn: 120 });
27
-
28
- return {
29
- key,
30
- signedUrl,
31
- };
32
- };
33
-
34
- /**
35
- * Generates a presigned URL for uploading a file to an S3 bucket.
36
- * @param {object} params - The parameters for generating the presigned URL.
37
- * @param {string} params.bucket - The S3 bucket name.
38
- * @param {string} params.fileName - The desired file name.
39
- * @returns {Promise<{key: string, signedUrl: string}>} The presigned URL.
40
- */
41
- export const generatePresignedUrl = async ({ prefix = '', bucket, fileName }: IGeneratePresignedUrl) => {
42
- const mime = getMime(fileName);
43
-
44
- const key = prefix + `${await generateString(10)}_${Date.now()}.` + mime;
45
-
46
- const command = new PutObjectCommand({ Bucket: bucket || config.aws.bucket, Key: key });
47
- const signedUrl = await getSignedUrl(s3Client, command, {
48
- expiresIn: msToSeconds(config.aws.uploadSignedUrlExpiresIn),
49
- });
50
- return {
51
- key,
52
- signedUrl,
53
- };
54
- };
55
-
56
- /**
57
- * Uploads multiple files to an S3 bucket.
58
- * @param {any[]} files - The array of files to upload.
59
- * @param {IOptions} [options] - The optional upload options.
60
- * @returns {Promise<IFileUploadResult[]>} The array of file upload results.
61
- */
62
- export const putFilesToBucket = async (files: any, options?: IPutFilesOptions): Promise<IFileUploadResult[]> => {
63
- let path = options?.path;
64
-
65
- const bucketName = options?.bucketName || config.aws.bucket;
66
-
67
- return await Promise.all(
68
- files.map(async (file: any) => {
69
- const fileContent = fs.readFileSync(file.path);
70
-
71
- const originalname = file.originalname;
72
- const mime = getMime(originalname);
73
-
74
- const filename = `${await generateString(10)}_${Date.now()}.` + mime;
75
- if (path) path = path.startsWith('/') ? path.replace('/', '') : `${path}`;
76
-
77
- // path from aws
78
- const key = path ? `${path}/${filename}` : filename;
79
- const filePath = `https://${bucketName}.s3.amazonaws.com/${key}`;
80
-
81
- const command = new PutObjectCommand({
82
- Bucket: bucketName,
83
- Key: key,
84
- Body: fileContent,
85
- });
86
-
87
- await s3Client.send(command);
88
-
89
- return {
90
- key,
91
- mime,
92
- completedUrl: filePath,
93
- originalFileName: originalname,
94
- createdAt: new Date(),
95
- };
96
- }),
97
- );
98
- };
99
-
100
- export const getFileSize = async (key: string): Promise<number> => {
101
- const getObjectMetaDataParams = {
102
- Bucket: config.aws.bucket,
103
- Key: key,
104
- };
105
-
106
- const response = await s3Client.send(new HeadObjectCommand(getObjectMetaDataParams));
107
- const sizeInBytes = response.ContentLength;
108
-
109
- if (!sizeInBytes) throw createError(httpStatus.NOT_FOUND, 'File not found');
110
-
111
- return sizeInBytes;
112
- };
113
-
114
- export const deleteFile = (key: string) => {
115
- const deleteObjectParams = {
116
- Bucket: config.aws.bucket,
117
- Key: key,
118
- };
119
-
120
- return s3Client.send(new DeleteObjectCommand(deleteObjectParams));
121
- };
File without changes