plenna_utilities 1.0.10 → 1.1.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.
@@ -1,28 +1,33 @@
1
- import docs from '@googleapis/docs';
1
+ import { docs_v1 } from '@googleapis/docs';
2
+ import { GoogleAuth, type JWTInput } from 'google-auth-library';
3
+ import { type JSONClient } from 'google-auth-library/build/src/auth/googleauth';
4
+ import { type IPlennaGoogleBase } from './requestBuilder';
5
+ interface cloneDocumentResponse {
6
+ success: boolean;
7
+ documentId?: string;
8
+ }
9
+ interface updateDocumentResponse {
10
+ success: boolean;
11
+ documentId?: string;
12
+ }
13
+ interface deleteDocumentResponse {
14
+ success: boolean;
15
+ documentId?: string;
16
+ }
17
+ export interface ISchemaRequest extends docs_v1.Schema$Request {
18
+ }
19
+ export interface ICredentials extends JWTInput {
20
+ }
2
21
  export declare class PlennaGoogleService {
3
- private credentials;
4
- constructor(credentials?: string);
5
- authorization(): Promise<import("google-auth-library").GoogleAuth<import("google-auth-library/build/src/auth/googleauth").JSONClient>>;
6
- getDocument(documentId: string): Promise<import("gaxios").GaxiosResponse<docs.docs_v1.Schema$Document> | undefined>;
7
- cloneDocument(documentId: string, folderId: string): Promise<{
8
- success: boolean;
9
- fileId?: string;
10
- }>;
11
- updateDocument(id: string, requests?: docs.docs_v1.Schema$Request[]): Promise<{
12
- success: boolean;
13
- updated: import("gaxios").GaxiosResponse<docs.docs_v1.Schema$BatchUpdateDocumentResponse>;
14
- } | {
15
- success: boolean;
16
- updated?: undefined;
17
- }>;
18
- exportDocument(fileId: string): Promise<ArrayBuffer | undefined>;
19
- deleteDocument(fileId: string): Promise<{
20
- success: boolean;
21
- deleted: import("gaxios").GaxiosResponse<void>;
22
- error?: undefined;
23
- } | {
24
- success: boolean;
25
- error: unknown;
26
- deleted?: undefined;
27
- }>;
22
+ private readonly credentials;
23
+ constructor(credentials: ICredentials);
24
+ authorization(): GoogleAuth<JSONClient>;
25
+ getDocument(documentId: string): Promise<docs_v1.Schema$Document | undefined>;
26
+ cloneDocument(documentId: string, folderId: string): Promise<cloneDocumentResponse>;
27
+ buildPayload(template?: IPlennaGoogleBase[]): ISchemaRequest[];
28
+ updateDocument(id: string, requests?: ISchemaRequest[]): Promise<updateDocumentResponse>;
29
+ exportDocumentAsUrl(fileId: string): Promise<string | undefined>;
30
+ exportDocumentAsFile(fileId: string): Promise<ArrayBuffer | undefined>;
31
+ deleteDocument(fileId: string): Promise<deleteDocumentResponse>;
28
32
  }
33
+ export {};
@@ -1,25 +1,18 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
2
  Object.defineProperty(exports, "__esModule", { value: true });
6
3
  exports.PlennaGoogleService = void 0;
7
- const docs_1 = __importDefault(require("@googleapis/docs"));
4
+ const docs_1 = require("@googleapis/docs");
8
5
  const drive_1 = require("@googleapis/drive");
9
- const { getSecret } = require('./secrets');
6
+ const google_auth_library_1 = require("google-auth-library");
7
+ const requestBuilder_1 = require("./requestBuilder");
10
8
  class PlennaGoogleService {
11
9
  credentials;
12
10
  constructor(credentials) {
13
11
  this.credentials = credentials;
14
12
  }
15
- async authorization() {
16
- let cred = this.credentials ?? '';
17
- if (cred === '') {
18
- console.log('getting credentials');
19
- cred = await getSecret('GoogleAuth') ?? '';
20
- }
21
- return new docs_1.default.auth.GoogleAuth({
22
- credentials: JSON.parse(cred),
13
+ authorization() {
14
+ return new google_auth_library_1.GoogleAuth({
15
+ credentials: this.credentials,
23
16
  scopes: [
24
17
  'https://www.googleapis.com/auth/documents',
25
18
  'https://www.googleapis.com/auth/drive'
@@ -27,8 +20,8 @@ class PlennaGoogleService {
27
20
  });
28
21
  }
29
22
  async getDocument(documentId) {
30
- const authClient = await this.authorization();
31
- const client = await docs_1.default.docs({ version: 'v1', auth: authClient });
23
+ const authClient = this.authorization();
24
+ const client = new docs_1.docs_v1.Docs({ auth: authClient });
32
25
  try {
33
26
  return await client.documents.get({ documentId });
34
27
  }
@@ -37,7 +30,7 @@ class PlennaGoogleService {
37
30
  }
38
31
  }
39
32
  async cloneDocument(documentId, folderId) {
40
- const authClient = await this.authorization();
33
+ const authClient = this.authorization();
41
34
  const gdrive = new drive_1.drive_v3.Drive({ auth: authClient });
42
35
  try {
43
36
  const fileId = await gdrive.files.copy({
@@ -48,61 +41,67 @@ class PlennaGoogleService {
48
41
  },
49
42
  fields: '*'
50
43
  });
51
- return { success: true, fileId: fileId?.data?.id ?? '' };
44
+ return { success: true, documentId: fileId?.data?.id ?? '' };
52
45
  }
53
46
  catch (error) {
54
47
  console.log(error);
55
48
  return { success: false };
56
49
  }
57
50
  }
51
+ buildPayload(template = []) {
52
+ return (0, requestBuilder_1.payloadBuilder)(template);
53
+ }
58
54
  async updateDocument(id, requests = []) {
59
- const authClient = await this.authorization();
60
- const client = await docs_1.default.docs({ version: 'v1', auth: authClient });
55
+ const authClient = this.authorization();
56
+ const client = new docs_1.docs_v1.Docs({ auth: authClient });
61
57
  try {
62
58
  const updated = await client.documents.batchUpdate({
63
59
  documentId: id,
64
- requestBody: {
65
- requests: requests
66
- }
60
+ requestBody: { requests }
67
61
  });
68
- return { success: true, updated };
62
+ return { success: true, documentId: updated?.data?.documentId ?? '' };
69
63
  }
70
64
  catch (error) {
71
65
  console.log(error);
72
66
  return { success: false };
73
67
  }
74
68
  }
75
- async exportDocument(fileId) {
76
- const authClient = await this.authorization();
69
+ async exportDocumentAsUrl(fileId) {
70
+ const authClient = this.authorization();
77
71
  const gdrive = new drive_1.drive_v3.Drive({ auth: authClient });
78
72
  try {
79
73
  const response = await gdrive.files.get({ fileId, fields: 'exportLinks' });
80
74
  const exportLinks = response?.data?.exportLinks ?? {};
81
75
  const link = exportLinks['application/pdf'];
82
- if (link === undefined) {
83
- throw new Error('not valid link received');
76
+ return link;
77
+ }
78
+ catch (error) {
79
+ console.log(error);
80
+ }
81
+ }
82
+ async exportDocumentAsFile(fileId) {
83
+ try {
84
+ const link = await this.exportDocumentAsUrl(fileId);
85
+ const token = await this.authorization().getAccessToken();
86
+ if (typeof link === 'string') {
87
+ const resp = await fetch(link, { headers: { Authorization: `Bearer ${token}` } });
88
+ return await resp.arrayBuffer();
84
89
  }
85
- const token = await authClient.getAccessToken();
86
- const file = await fetch(link, {
87
- headers: { Authorization: `Bearer ${token}` }
88
- });
89
- console.log({ file });
90
- return file.arrayBuffer();
91
90
  }
92
91
  catch (error) {
93
92
  console.log(error);
94
93
  }
95
94
  }
96
95
  async deleteDocument(fileId) {
97
- const authClient = await this.authorization();
96
+ const authClient = this.authorization();
98
97
  const gdrive = new drive_1.drive_v3.Drive({ auth: authClient });
99
98
  try {
100
- const deleted = await gdrive.files.delete({ fileId });
101
- return { success: true, deleted };
99
+ await gdrive.files.delete({ fileId });
100
+ return { success: true, documentId: fileId };
102
101
  }
103
102
  catch (error) {
104
103
  console.log(error);
105
- return { success: false, error };
104
+ return { success: false };
106
105
  }
107
106
  }
108
107
  }
@@ -0,0 +1,10 @@
1
+ import { type docs_v1 } from '@googleapis/docs';
2
+ export type documentType = 'text' | 'image';
3
+ export interface ISchemaRequest extends docs_v1.Schema$Request {
4
+ }
5
+ export interface IPlennaGoogleBase {
6
+ doc_type: documentType;
7
+ identifier: string;
8
+ value: string;
9
+ }
10
+ export declare const payloadBuilder: (template: IPlennaGoogleBase[]) => docs_v1.Schema$Request[];
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.payloadBuilder = void 0;
4
+ const getPayload = (type, variable, value) => {
5
+ if (variable === undefined) {
6
+ return undefined;
7
+ }
8
+ if (value === undefined) {
9
+ return undefined;
10
+ }
11
+ const templates = {
12
+ text: {
13
+ replaceAllText: {
14
+ containsText: {
15
+ text: `[${variable}]`,
16
+ matchCase: true
17
+ },
18
+ replaceText: value
19
+ }
20
+ },
21
+ image: {
22
+ replaceImage: {
23
+ imageObjectId: variable,
24
+ uri: value
25
+ }
26
+ }
27
+ };
28
+ return templates[type];
29
+ };
30
+ const payloadBuilder = (template) => {
31
+ const payload = [];
32
+ template.forEach(field => {
33
+ const val = getPayload(field.doc_type, field.identifier, field.value);
34
+ if (val !== undefined) {
35
+ payload.push(val);
36
+ }
37
+ });
38
+ console.log(payload);
39
+ return payload.filter(v => v);
40
+ };
41
+ exports.payloadBuilder = payloadBuilder;
@@ -1,7 +1,9 @@
1
- import { ObjectCannedACL } from "@aws-sdk/client-s3";
1
+ import { type ObjectCannedACL, type PutObjectCommandInput } from '@aws-sdk/client-s3';
2
2
  export declare class PlennaS3Service {
3
3
  private readonly bucket;
4
4
  private readonly acl;
5
- constructor(bucket: string, acl: ObjectCannedACL);
5
+ private readonly options;
6
+ constructor(bucket: string, acl: ObjectCannedACL, options?: Partial<PutObjectCommandInput>);
6
7
  getPresignedUrl(keyName: string): Promise<string>;
8
+ upload(fileName: string, file: PutObjectCommandInput['Body'], options?: Partial<PutObjectCommandInput>): Promise<string>;
7
9
  }
@@ -3,16 +3,20 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.PlennaS3Service = void 0;
4
4
  const client_s3_1 = require("@aws-sdk/client-s3");
5
5
  const s3_request_presigner_1 = require("@aws-sdk/s3-request-presigner");
6
+ const REGION = 'us-east-2';
6
7
  class PlennaS3Service {
7
8
  bucket;
8
9
  acl;
9
- constructor(bucket, acl) {
10
+ options;
11
+ constructor(bucket, acl, options = {}) {
10
12
  this.bucket = bucket;
11
13
  this.acl = acl;
14
+ this.options = options;
12
15
  }
13
16
  async getPresignedUrl(keyName) {
14
- const s3Client = new client_s3_1.S3Client({ region: 'us-east-2' });
17
+ const s3Client = new client_s3_1.S3Client({ region: REGION });
15
18
  const command = new client_s3_1.PutObjectCommand({
19
+ ...this.options,
16
20
  Bucket: this.bucket,
17
21
  Key: keyName,
18
22
  ACL: this.acl
@@ -20,5 +24,21 @@ class PlennaS3Service {
20
24
  const signedUrl = await (0, s3_request_presigner_1.getSignedUrl)(s3Client, command, { expiresIn: 3600 });
21
25
  return signedUrl;
22
26
  }
27
+ async upload(fileName, file, options = {}) {
28
+ const s3 = new client_s3_1.S3Client({ region: REGION });
29
+ console.log('received file:', fileName);
30
+ const uploadParams = {
31
+ ...this.options,
32
+ ...options,
33
+ Bucket: this.bucket,
34
+ Key: fileName,
35
+ Body: file,
36
+ ACL: this.acl
37
+ };
38
+ const response = await s3.send(new client_s3_1.PutObjectCommand(uploadParams));
39
+ console.log(response.ETag);
40
+ const fileS3Url = `https://${this.bucket}.s3.${REGION}.amazonaws.com/${fileName}`;
41
+ return fileS3Url;
42
+ }
23
43
  }
24
44
  exports.PlennaS3Service = PlennaS3Service;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "plenna_utilities",
3
- "version": "1.0.10",
3
+ "version": "1.1.0",
4
4
  "description": "plenna's utils for backend projects",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -8,7 +8,8 @@
8
8
  "dist/"
9
9
  ],
10
10
  "scripts": {
11
- "build": "tsc"
11
+ "lint": "rm -rf dist && eslint '**/*.{ts,tsx}'",
12
+ "build": "npm run lint && tsc"
12
13
  },
13
14
  "repository": {
14
15
  "type": "git"
@@ -21,15 +22,22 @@
21
22
  "author": "@plenna",
22
23
  "license": "ISC",
23
24
  "devDependencies": {
24
- "@types/aws-lambda": "^8.10.138",
25
- "@types/node": "^20.14.2",
25
+ "@types/aws-lambda": "^8.10.140",
26
+ "@types/node": "^20.14.5",
27
+ "@typescript-eslint/eslint-plugin": "^6.21.0",
28
+ "eslint": "^8.57.0",
29
+ "eslint-config-standard-with-typescript": "^43.0.1",
30
+ "eslint-plugin-import": "^2.29.1",
31
+ "eslint-plugin-n": "^16.6.2",
32
+ "eslint-plugin-promise": "^6.1.1",
26
33
  "typescript": "^5.4.5"
27
34
  },
28
35
  "dependencies": {
29
- "@aws-sdk/client-s3": "^3.596.0",
30
- "@aws-sdk/s3-request-presigner": "^3.596.0",
36
+ "@aws-sdk/client-s3": "^3.600.0",
37
+ "@aws-sdk/s3-request-presigner": "^3.600.0",
31
38
  "@googleapis/docs": "^3.0.2",
32
39
  "@googleapis/drive": "^8.10.0",
33
- "@googleapis/sheets": "^8.0.0"
40
+ "@googleapis/sheets": "^8.0.0",
41
+ "google-auth-library": "^9.11.0"
34
42
  }
35
- }
43
+ }