├── index.js ├── index.d.ts ├── LICENSE ├── package.json ├── README.md ├── .gitignore ├── src └── services │ └── gcp.ts └── tsconfig.json /index.js: -------------------------------------------------------------------------------- 1 | //noop -------------------------------------------------------------------------------- /index.d.ts: -------------------------------------------------------------------------------- 1 | export type PluginOptions = { 2 | /** 3 | * GCP BUCKET NAME 4 | */ 5 | bucket: string; 6 | /** 7 | * private_key and client_email from GCP service account json 8 | * https://cloud.google.com/iam/docs/service-account-overview/ 9 | */ 10 | credentials: { 11 | client_email: string; 12 | private_key: string; 13 | } 14 | 15 | /** 16 | * fileNaming: "original" | "random" | "original_random", 17 | * @default: "original_random" 18 | */ 19 | 20 | fileNaming?: "original" | "random" | "original_random"; 21 | }; -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Glenford Williams 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "medusa-file-gcp", 3 | "version": "1.0.0", 4 | "description": "Google cloud storage plugin for medusajs", 5 | "main": "index.js", 6 | "author": "Glenford Williams", 7 | "license": "MIT", 8 | "repository": { 9 | "type": "git", 10 | "url": "https://github.com/drewdecarme/medusa-file-cloudflare-images" 11 | }, 12 | "keywords": [ 13 | "medusa", 14 | "gcp", 15 | "google cloud", 16 | "filestorage", 17 | "medusa-plugin" 18 | ], 19 | "scripts": { 20 | "bundle": "esbuild src/services/** --outdir=services --format=cjs --target=esnext", 21 | "bundle-swc": "swc src -d .", 22 | "build": "yarn bundle", 23 | "build:ci": "yarn bundle", 24 | "prepare": "yarn build", 25 | "dev": "yarn bundle --watch", 26 | "test": "jest", 27 | "package": "yarn build && yarn np --no-tests --no-yarn" 28 | }, 29 | "peerDependencies": { 30 | "medusa-interfaces": "1.x" 31 | }, 32 | "files": [ 33 | "services" 34 | ], 35 | "devDependencies": { 36 | "@types/formidable": "^2.0.3", 37 | "@types/nanoid": "^3.0.0", 38 | "chokidar": "^3.5.2", 39 | "client-sessions": "^0.8.0", 40 | "cross-env": "^7.0.3", 41 | "esbuild": "^0.14.10", 42 | "eslint": "^8.6.0", 43 | "jest": "^27.4.7", 44 | "typescript": "^4.5.4" 45 | }, 46 | "dependencies": { 47 | "@google-cloud/storage": "^7.6.0", 48 | "body-parser": "^1.19.1", 49 | "express": "^4.17.2", 50 | "form-data": "^4.0.0", 51 | "formidable": "^2.0.1", 52 | "medusa-core-utils": "^1.1.31", 53 | "medusa-interfaces": "^1.1.34", 54 | "medusa-test-utils": "^1.1.36", 55 | "nanoid": "^3.3.6", 56 | "node-fetch": "2.6.6", 57 | "np": "^7.6.0", 58 | "regenerator-runtime": "^0.13.9", 59 | "typeorm": "^0.2.41" 60 | }, 61 | "packageManager": "yarn@3.1.1" 62 | } 63 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Medusa File Google Cloud Storage Images 2 | 3 | Google Cloud Platform (GCP) storage plugin for Medusa.js 4 | 5 | ## Prerequisites 6 | 7 | - [Medusa backend](https://docs.medusajs.com/development/backend/install/) 8 | - [Google Cloud Platform (GCP)](https://cloud.google.com/) 9 | 10 | ## How to install 11 | 12 | 1. Run the following command in the directory of your Medusa backend: 13 | 14 | ``` 15 | npm install medusa-plugin-gcp 16 | ``` 17 | 18 | 2. Add following environment variables into your `.env`: 19 | 20 | ``` 21 | GCP_BUCKET= 22 | GCP_PRIVATE_KEY= 23 | GCP_CLIENT_EMAIL= 24 | ``` 25 | 26 | 3. Open your `medusa.config.js` and add the below configuration: 27 | 28 | ```js 29 | module.exports = { 30 | plugins: [ 31 | ...otherMedusaPlugins, 32 | { 33 | resolve: `medusa-plugin-gcp`, 34 | /** @type {import('medusa-plugin-gcp').PluginOptions} */ 35 | options: { 36 | bucket: process.env.GCP_BUCKET, 37 | fileNaming: "original_random", // @default to original_random, options: original, random, original_random 38 | credentials: { 39 | private_key: process.env.GCP_PRIVATE_KEY, 40 | client_email: process.env.GCP_CLIENT_EMAIL, 41 | }, 42 | }, 43 | }, 44 | ], 45 | }; 46 | ``` 47 | 48 | ## Test the plugin 49 | 50 | 1. Run your Medusa backend: 51 | 52 | ``` 53 | npm run dev 54 | ``` 55 | 56 | 2. Try to upload an image for a product using Medusa's admin interface. The image should appear into your storage bucket. 57 | 58 | ## Additional resources 59 | 60 | - [GCP Storage Buckets](Bucketshttps://cloud.google.com/storage/docs/creating-buckets/) 61 | - [GCP Service Accounts](https://cloud.google.com/iam/docs/service-account-overview/) 62 | - [@google-cloud/storage (package)](https://www.npmjs.com/package/@google-cloud/storage/) 63 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | 9 | # Diagnostic reports (https://nodejs.org/api/report.html) 10 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 11 | 12 | # Runtime data 13 | pids 14 | *.pid 15 | *.seed 16 | *.pid.lock 17 | 18 | # Directory for instrumented libs generated by jscoverage/JSCover 19 | lib-cov 20 | 21 | # Coverage directory used by tools like istanbul 22 | coverage 23 | *.lcov 24 | 25 | # nyc test coverage 26 | .nyc_output 27 | 28 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 29 | .grunt 30 | 31 | # Bower dependency directory (https://bower.io/) 32 | bower_components 33 | 34 | # node-waf configuration 35 | .lock-wscript 36 | 37 | # Compiled binary addons (https://nodejs.org/api/addons.html) 38 | build/Release 39 | 40 | # Dependency directories 41 | node_modules/ 42 | jspm_packages/ 43 | 44 | # TypeScript v1 declaration files 45 | typings/ 46 | 47 | # TypeScript cache 48 | *.tsbuildinfo 49 | 50 | # Optional npm cache directory 51 | .npm 52 | 53 | # Optional eslint cache 54 | .eslintcache 55 | 56 | # Microbundle cache 57 | .rpt2_cache/ 58 | .rts2_cache_cjs/ 59 | .rts2_cache_es/ 60 | .rts2_cache_umd/ 61 | 62 | # Optional REPL history 63 | .node_repl_history 64 | 65 | # Output of 'npm pack' 66 | *.tgz 67 | 68 | # Yarn Integrity file 69 | .yarn-integrity 70 | 71 | # dotenv environment variables file 72 | .env 73 | .env.test 74 | 75 | # parcel-bundler cache (https://parceljs.org/) 76 | .cache 77 | 78 | # Next.js build output 79 | .next 80 | 81 | # Nuxt.js build / generate output 82 | .nuxt 83 | dist 84 | 85 | # Gatsby files 86 | .cache/ 87 | # Comment in the public line in if your project uses Gatsby and *not* Next.js 88 | # https://nextjs.org/blog/next-9-1#public-directory-support 89 | # public 90 | 91 | # vuepress build output 92 | .vuepress/dist 93 | 94 | # Serverless directories 95 | .serverless/ 96 | 97 | # FuseBox cache 98 | .fusebox/ 99 | 100 | # DynamoDB Local files 101 | .dynamodb/ 102 | 103 | # TernJS port file 104 | .tern-port 105 | -------------------------------------------------------------------------------- /src/services/gcp.ts: -------------------------------------------------------------------------------- 1 | import { FileService } from "medusa-interfaces"; 2 | import { Storage, UploadResponse } from "@google-cloud/storage"; 3 | import stream from "stream"; 4 | import { GetSignedUrlConfig } from "@google-cloud/storage"; 5 | import { nanoid } from "nanoid"; 6 | 7 | export interface CredentialBody { 8 | client_email?: string; 9 | private_key?: string; 10 | } 11 | 12 | export interface GcpStorageServiceOptions { 13 | credentials: CredentialBody, 14 | bucket: string, 15 | fileNaming?: "original" | "random" | "original_random", 16 | } 17 | 18 | class GcpStorageService extends FileService { 19 | bucket_: any; 20 | credentials_: CredentialBody; 21 | gcsBaseUrl: string; 22 | fileNaming: "original" | "random" | "original_random" = "original_random"; 23 | 24 | constructor({ }: any, options: GcpStorageServiceOptions) { 25 | super(); 26 | this.bucket_ = options.bucket; 27 | this.credentials_ = options.credentials; 28 | this.gcsBaseUrl = `https://storage.googleapis.com/${this.bucket_}/`; 29 | this.fileNaming = options.fileNaming || "original_random"; 30 | } 31 | 32 | storage() { 33 | return new Storage({ 34 | credentials: this.credentials_ 35 | }); 36 | } 37 | 38 | upload(file: { path: string; originalname: string; }) { 39 | let fileName = file.originalname; 40 | const fileWihoutExt = file.originalname.split('.').shift(); 41 | const fileExt = file.originalname.split('.').pop(); 42 | 43 | switch (this.fileNaming) { 44 | case "original": 45 | fileName = file.originalname; 46 | break; 47 | case "random": 48 | fileName = nanoid(10) + `.${fileExt}`; 49 | break; 50 | case "original_random": 51 | fileName = `${fileWihoutExt}_${nanoid(10)}.${fileExt}`; 52 | break; 53 | default: 54 | fileName = nanoid(10) + `.${fileExt}`; 55 | break; 56 | } 57 | return new Promise((resolve, reject) => { 58 | 59 | this.storage().bucket(this.bucket_).upload(file.path, { 60 | destination: fileName, 61 | public: true 62 | }).then((result: UploadResponse) => { 63 | const bucket_file = this.storage().bucket(this.bucket_).file(fileName); 64 | resolve({ url: bucket_file.publicUrl() }); 65 | }).catch((err: any) => { 66 | console.error(err) 67 | reject(err); 68 | }); 69 | 70 | }) 71 | } 72 | 73 | delete(fileName: string) { 74 | return new Promise((resolve, reject) => { 75 | this.storage() 76 | .bucket(this.bucket_) 77 | .file(fileName) 78 | .delete() 79 | .then((res) => { 80 | resolve(res); 81 | }) 82 | .catch((err) => { 83 | reject(err); 84 | }); 85 | }); 86 | } 87 | 88 | async getDownloadStream({ ...fileData }) { 89 | return this.storage() 90 | .bucket(this.bucket_) 91 | .file(fileData.fileKey) 92 | .createReadStream() 93 | } 94 | 95 | async getUploadStreamDescriptor({ ...fileData }) { 96 | const fileKey = `${fileData.name}.${fileData.ext}`; 97 | const pass = new stream.PassThrough(); 98 | 99 | return { 100 | writeStream: pass, 101 | promise: pass.pipe(this.storage().bucket(this.bucket_).file(fileKey).createWriteStream()), 102 | url: `${this.gcsBaseUrl}/${fileKey}`, 103 | fileKey, 104 | } 105 | } 106 | 107 | async getPresignedDownloadUrl({ ...fileData }) { 108 | const fileKey = fileData.fileKey; 109 | 110 | const options = { 111 | version: 'v4', 112 | action: 'read', 113 | expires: Date.now() + 15 * 60 * 1000, // 15 MINUTES 114 | } as GetSignedUrlConfig 115 | 116 | 117 | return (this.storage() 118 | .bucket(this.bucket_) 119 | .file(fileKey) 120 | .getSignedUrl(options)) 121 | } 122 | } 123 | 124 | export default GcpStorageService; -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Visit https://aka.ms/tsconfig.json to read more about this file */ 4 | 5 | /* Projects */ 6 | "incremental": true /* Enable incremental compilation */, 7 | // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ 8 | // "tsBuildInfoFile": "./", /* Specify the folder for .tsbuildinfo incremental compilation files. */ 9 | // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects */ 10 | // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ 11 | // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ 12 | 13 | /* Language and Environment */ 14 | "target": "es2016" /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */, 15 | // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ 16 | // "jsx": "preserve", /* Specify what JSX code is generated. */ 17 | // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */ 18 | // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ 19 | // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h' */ 20 | // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ 21 | // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using `jsx: react-jsx*`.` */ 22 | // "reactNamespace": "", /* Specify the object invoked for `createElement`. This only applies when targeting `react` JSX emit. */ 23 | // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ 24 | // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ 25 | 26 | /* Modules */ 27 | "module": "commonjs" /* Specify what module code is generated. */, 28 | // "rootDir": "./", /* Specify the root folder within your source files. */ 29 | "moduleResolution": "node" /* Specify how TypeScript looks up a file from a given module specifier. */, 30 | // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ 31 | // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ 32 | // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ 33 | // "typeRoots": [], /* Specify multiple folders that act like `./node_modules/@types`. */ 34 | // "types": [], /* Specify type package names to be included without being referenced in a source file. */ 35 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 36 | "resolveJsonModule": true /* Enable importing .json files */, 37 | // "noResolve": true, /* Disallow `import`s, `require`s or ``s from expanding the number of files TypeScript should add to a project. */ 38 | 39 | /* JavaScript Support */ 40 | // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */ 41 | // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ 42 | // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from `node_modules`. Only applicable with `allowJs`. */ 43 | 44 | /* Emit */ 45 | "declaration": true /* Generate .d.ts files from TypeScript and JavaScript files in your project. */, 46 | "declarationMap": true /* Create sourcemaps for d.ts files. */, 47 | "emitDeclarationOnly": true /* Only output d.ts files and not JavaScript files. */, 48 | "sourceMap": true /* Create source map files for emitted JavaScript files. */, 49 | // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If `declaration` is true, also designates a file that bundles all .d.ts output. */ 50 | // "outDir": "./", /* Specify an output folder for all emitted files. */ 51 | // "removeComments": true, /* Disable emitting comments. */ 52 | // "noEmit": true, /* Disable emitting files from a compilation. */ 53 | // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ 54 | // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types */ 55 | "downlevelIteration": true /* Emit more compliant, but verbose and less performant JavaScript for iteration. */, 56 | // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ 57 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 58 | // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ 59 | // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ 60 | // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ 61 | // "newLine": "crlf", /* Set the newline character for emitting files. */ 62 | // "stripInternal": true, /* Disable emitting declarations that have `@internal` in their JSDoc comments. */ 63 | // "noEmitHelpers": true, /* Disable generating custom helper functions like `__extends` in compiled output. */ 64 | // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ 65 | // "preserveConstEnums": true, /* Disable erasing `const enum` declarations in generated code. */ 66 | // "declarationDir": "./", /* Specify the output directory for generated declaration files. */ 67 | // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */ 68 | 69 | /* Interop Constraints */ 70 | // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ 71 | // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ 72 | "esModuleInterop": true /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */, 73 | // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ 74 | "forceConsistentCasingInFileNames": true /* Ensure that casing is correct in imports. */, 75 | 76 | /* Type Checking */ 77 | "strict": true /* Enable all strict type-checking options. */, 78 | "noImplicitAny": true /* Enable error reporting for expressions and declarations with an implied `any` type.. */, 79 | "strictNullChecks": true /* When type checking, take into account `null` and `undefined`. */, 80 | // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ 81 | // "strictBindCallApply": true, /* Check that the arguments for `bind`, `call`, and `apply` methods match the original function. */ 82 | // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ 83 | "noImplicitThis": true /* Enable error reporting when `this` is given the type `any`. */, 84 | "useUnknownInCatchVariables": true /* Type catch clause variables as 'unknown' instead of 'any'. */, 85 | "alwaysStrict": true /* Ensure 'use strict' is always emitted. */, 86 | "noUnusedLocals": true /* Enable error reporting when a local variables aren't read. */, 87 | // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read */ 88 | // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ 89 | // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ 90 | // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ 91 | // "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */ 92 | // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ 93 | // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type */ 94 | // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ 95 | // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ 96 | 97 | /* Completeness */ 98 | // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ 99 | "skipLibCheck": true /* Skip type checking all .d.ts files. */ 100 | } 101 | } --------------------------------------------------------------------------------