feat(medusa-plugin-mailchimp): Migrate to TS + add update endpoint (#4040)

* - Refactored the .js files to .ts files
- Added typing
- Used 'WrapHandler' util instead of specific middleware in plugin
- Added additional PUT method to the /mailchimp/subscribe endpoint.
- Updated documentation where relevant.

* Added changeset

* Updated yarn.lock

* Used camelcase for method args in services/mailchimp.ts

---------

Co-authored-by: Tom Rupke <tom@adapptive.nl>
Co-authored-by: Oliver Windall Juhl <59018053+olivermrbl@users.noreply.github.com>
This commit is contained in:
authored and GitHub committed 2023-05-23 13:33:56 +02:00
1 parent 5c01b4e6b6
commit ddc90db530
19 files changed
+401 -158

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
"medusa-plugin-mailchimp": patch
---
feat(medusa-plugin-mailchimp): Added PUT method for the /mailchimp/subscribe endpoint.
@@ -80,11 +80,11 @@ const plugins = [
## Test it Out
This plugin adds a new `POST` endpoint at `/mailchimp/subscribe`. This endpoint requires in the body of the request an `email` field. You can also optionally include a `data` object that holds any additional data you want to send to Mailchimp. You can check out [Mailchimp’s subscription documentation](https://mailchimp.com/developer/marketing/api/list-members/add-member-to-list/) for more details on the data you can send.
This plugin adds new `POST` and `PUT` endpoints at `/mailchimp/subscribe`. These endpoints require in the body of the request an `email` field. You can also optionally include a `data` object that holds any additional data you want to send to Mailchimp. You can check out [Mailchimp’s subscription documentation](https://mailchimp.com/developer/marketing/api/list-merges/) for more details on the data you can send.
### Without Additional Data
Try sending a `POST` request to `/mailchimp/subscribe` with the following JSON body:
Try sending a `POST` or `PUT` request to `/mailchimp/subscribe` with the following JSON body:
```json noReport
{
@@ -92,7 +92,7 @@ Try sending a `POST` request to `/mailchimp/subscribe` with the following JSON b
}
```
If the subscription is successful, a `200` response code will be returned with `OK` message.
If the subscription is successful, a `200` response code will be returned with `OK` message. If the same email address is used again in the `POST`, a `400` response will be returned with an error page. If this can occur in your usecase, use the `PUT` endpoint to prevent this.
![Postman](https://res.cloudinary.com/dza7lstvk/image/upload/v1668000185/Medusa%20Docs/Mailchimp/tpr7uCF_g4rymn.png)
+22 -23
View File
@@ -22,32 +22,31 @@ Manage newsletter subscriptions in your commerce application with Mailchimp.
1\. Run the following command in the directory of the Medusa backend:
```bash
npm install medusa-plugin-mailchimp
```
```bash
npm install medusa-plugin-mailchimp
```
2\. Set the following environment variables in `.env`:
```bash
MAILCHIMP_API_KEY=<YOUR_API_KEY>
MAILCHIMP_NEWSLETTER_LIST_ID=<YOUR_NEWSLETTER_LIST_ID>
```
```bash
MAILCHIMP_API_KEY=<YOUR_API_KEY>
MAILCHIMP_NEWSLETTER_LIST_ID=<YOUR_NEWSLETTER_LIST_ID>
```
3\. In `medusa-config.js` add the following at the end of the `plugins` array:
```js
const plugins = [
// ...,
{
resolve: `medusa-plugin-mailchimp`,
options: {
api_key: process.env.MAILCHIMP_API_KEY,
newsletter_list_id:
process.env.MAILCHIMP_NEWSLETTER_LIST_ID,
},
```js
const plugins = [
// ...,
{
resolve: `medusa-plugin-mailchimp`,
options: {
api_key: process.env.MAILCHIMP_API_KEY,
newsletter_list_id: process.env.MAILCHIMP_NEWSLETTER_LIST_ID,
},
]
```
},
]
```
---
@@ -55,11 +54,11 @@ Manage newsletter subscriptions in your commerce application with Mailchimp.
1\. Run the following command in the directory of the Medusa backend to run the backend:
```bash
npm run start
```
```bash
npm run start
```
2\. Use the `/mailchimp/subscribe` endpoint or the `MailchimpService` to subscribe to the newsletter.
2\. Use the POST or PUT `/mailchimp/subscribe` endpoint or the `MailchimpService` to subscribe to the newsletter.
---
+7 -15
View File
@@ -8,34 +8,26 @@
"url": "https://github.com/medusajs/medusa",
"directory": "packages/medusa-plugin-mailchimp"
},
"author": "Oliver Juhl",
"author": "Oliver Juhl, Tomek Pur",
"license": "MIT",
"devDependencies": {
"@babel/cli": "^7.7.5",
"@babel/core": "^7.7.5",
"@babel/node": "^7.7.4",
"@babel/plugin-proposal-class-properties": "^7.7.4",
"@babel/plugin-transform-instanceof": "^7.8.3",
"@babel/plugin-transform-runtime": "^7.7.6",
"@babel/preset-env": "^7.7.5",
"@babel/register": "^7.7.4",
"@babel/runtime": "^7.9.6",
"@medusajs/medusa": "1.10.0",
"@types/express": "^4.17.17",
"client-sessions": "^0.8.0",
"cross-env": "^5.2.1",
"jest": "^25.5.4",
"medusa-interfaces": "^1.3.7"
"typescript": "^4.4.4"
},
"scripts": {
"prepare": "cross-env NODE_ENV=production yarn run build",
"test": "jest --passWithNoTests src",
"build": "babel src --out-dir . --ignore '**/__tests__','**/__mocks__'",
"watch": "babel -w src --out-dir . --ignore '**/__tests__','**/__mocks__'"
"build": "tsc",
"watch": "tsc --watch"
},
"peerDependencies": {
"medusa-interfaces": "1.3.7"
"@medusajs/medusa": "1.10.0"
},
"dependencies": {
"@babel/plugin-transform-classes": "^7.9.5",
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"express": "^4.17.1",
@@ -1,7 +1,7 @@
import { Router } from "express"
import routes from "./routes"
export default (rootDirectory) => {
export default function (rootDirectory: string): Router | Router[] {
const app = Router()
routes(app, rootDirectory)
@@ -1 +0,0 @@
export default (fn) => (...args) => fn(...args).catch(args[2])
@@ -1,5 +0,0 @@
import { default as wrap } from "./await-middleware"
export default {
wrap,
}
@@ -1,30 +0,0 @@
import { Router } from "express"
import bodyParser from "body-parser"
import middlewares from "../middleware"
import { getConfigFile, parseCorsOrigins } from "medusa-core-utils"
import cors from "cors"
const route = Router()
export default (app, rootDirectory) => {
const { configModule } = getConfigFile(rootDirectory, `medusa-config`)
const config = (configModule && configModule.projectConfig) || {}
const storeCors = config.store_cors || ""
route.use(
cors({
origin: parseCorsOrigins(storeCors),
credentials: true,
})
)
app.use("/mailchimp", route)
route.post(
"/subscribe",
bodyParser.json(),
middlewares.wrap(require("./subscribe-newsletter").default)
)
return app
}
@@ -0,0 +1,39 @@
import { Router } from "express"
import * as cors from "cors"
import * as bodyParser from "body-parser"
import configLoader from "@medusajs/medusa/dist/loaders/config"
import { parseCorsOrigins } from "medusa-core-utils"
import { wrapHandler } from "@medusajs/medusa"
import {
update as subscribeNewsletterUpdate,
add as subscribeNewsletterAdd,
} from "./subscribe-newsletter"
const router = Router()
export default (app: Router, rootDirectory) => {
const config = configLoader(rootDirectory)
const corsOptions = {
origin: parseCorsOrigins(config.projectConfig.store_cors || ""),
credentials: true,
}
app.use("/mailchimp", router)
router.use(cors(corsOptions))
router.post(
"/subscribe",
bodyParser.json(),
wrapHandler(subscribeNewsletterAdd)
)
router.put(
"/subscribe",
bodyParser.json(),
wrapHandler(subscribeNewsletterUpdate)
)
return app
}
@@ -1,8 +0,0 @@
export default async (req, res) => {
const mailchimpService = req.scope.resolve("mailchimpService")
await mailchimpService.subscribeNewsletter(
req.body.email,
req.body.data || {}
)
res.sendStatus(200)
}
@@ -0,0 +1,19 @@
import { Request, Response } from "express"
export async function add(req: Request, res: Response) {
const mailchimpService = req.scope.resolve("mailchimpService")
await mailchimpService.subscribeNewsletterAdd(
req.body.email,
req.body.data || {}
)
res.sendStatus(200)
}
export async function update(req: Request, res: Response) {
const mailchimpService = req.scope.resolve("mailchimpService")
await mailchimpService.subscribeNewsletterUpdate(
req.body.email,
req.body.data || {}
)
res.sendStatus(200)
}
@@ -1,21 +0,0 @@
const MailchimpMock = jest.fn().mockImplementation(() => {
return {
subscribeNewsletter: jest.fn().mockReturnValue(Promise.resolve("success")),
}
})
describe("MailchimpService", () => {
describe("newsletterSubscribe", () => {
let result
beforeAll(async () => {
jest.clearAllMocks()
const mailchimpService = new MailchimpMock()
result = await mailchimpService.subscribeNewsletter("medusa@medusa.com")
})
it("resolves successfully", () => {
expect(result).toEqual("success")
})
})
})
@@ -0,0 +1,43 @@
const MailchimpMock = jest.fn().mockImplementation(() => {
return {
subscribeNewsletterAdd: jest
.fn()
.mockReturnValue(Promise.resolve("success")),
subscribeNewsletterUpdate: jest
.fn()
.mockReturnValue(Promise.resolve("success")),
}
})
describe("MailchimpService", () => {
describe("newsletterSubscribe", () => {
let result
beforeAll(async () => {
jest.clearAllMocks()
const mailchimpService = new MailchimpMock()
result = await mailchimpService.subscribeNewsletterAdd(
"medusa@medusa.com"
)
})
it("resolves successfully", () => {
expect(result).toEqual("success")
})
}),
describe("newsletterSubscribeUpdate", () => {
let result
beforeAll(async () => {
jest.clearAllMocks()
const mailchimpService = new MailchimpMock()
result = await mailchimpService.subscribeNewsletterUpdate(
"medusa@medusa.com"
)
})
it("resolves successfully", () => {
expect(result).toEqual("success")
})
})
})
@@ -1,39 +0,0 @@
import { BaseService } from "medusa-interfaces"
import Mailchimp from "mailchimp-api-v3"
class MailchimpService extends BaseService {
/**
* @param {Object} options - options defined in `medusa-config.js`
* e.g.
* {
* api_key: Mailchimp api key
* newsletter_list_id: "123456789"
* }
*/
constructor({}, options) {
super()
this.options_ = options
this.mailchimp_ = new Mailchimp(options.api_key)
}
/**
* Subscribes an email to a newsletter.
* @param {string} email - email to use for the subscription
* @param {Object} data - additional data (see https://mailchimp.com/developer/api/marketing/list-members/add-member-to-list/)
* @return {Promise} result of newsletter subscription
*/
async subscribeNewsletter(email, data) {
return this.mailchimp_.post(
`/lists/${this.options_.newsletter_list_id}/members`,
{
email_address: email,
status: "subscribed",
...data,
}
)
}
}
export default MailchimpService
@@ -0,0 +1,71 @@
import { TransactionBaseService } from "@medusajs/medusa"
import Mailchimp = require("mailchimp-api-v3")
import * as crypto from "crypto"
import { MailchimpPluginOptions } from "../types"
class MailchimpService extends TransactionBaseService {
protected options_: MailchimpPluginOptions
protected mailchimp_: Mailchimp
/**
* @param {Object} options - options defined in `medusa-config.js`
* e.g.
* {
* api_key: Mailchimp api key
* newsletter_list_id: "123456789"
* }
*/
constructor(_, options: MailchimpPluginOptions) {
super(_, options)
this.options_ = options
this.mailchimp_ = new Mailchimp(options.api_key)
}
/**
* Subscribes an email to a newsletter.
* @param {string} email - email to use for the subscription
* @param {Object} data - additional data (see https://mailchimp.com/developer/marketing/api/list-merges/)
* @return {Promise} result of newsletter subscription
*/
async subscribeNewsletterAdd(email: string, data: any) {
return this.mailchimp_.post(
`/lists/${this.options_.newsletter_list_id}/members`,
{
email_address: email,
status: "subscribed",
...data,
}
)
}
/**
* Updates an email to a newsletter.
* @param {string} email - email to use for the subscription
* @param {Object} data - additional data (see https://mailchimp.com/developer/marketing/api/list-merges/)
* @return {Promise} result of newsletter subscription
*/
async subscribeNewsletterUpdate(
email: string,
data: any,
statusIfNew?: string,
status?: string
) {
const lowercase = email.toLowerCase()
const hash = crypto.createHash("md5").update(lowercase).digest("hex")
return this.mailchimp_.put(
`/lists/${this.options_.newsletter_list_id}/members/${hash}`,
{
email_address: email,
status_if_new: statusIfNew || "subscribed",
status: status || "subscribed",
...data,
}
)
}
}
export default MailchimpService
@@ -0,0 +1,4 @@
export type MailchimpPluginOptions = {
newsletter_list_id: string
api_key: string
}
@@ -0,0 +1,27 @@
{
"compilerOptions": {
"lib": ["es5", "es6"],
"target": "esnext",
"allowJs": true,
"esModuleInterop": false,
"module": "commonjs",
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"skipLibCheck": true,
"skipDefaultLibCheck": true,
"declaration": false,
"sourceMap": false,
"outDir": "./dist",
"rootDir": "src",
"baseUrl": "src"
},
"include": ["src"],
"exclude": [
"dist",
"./src/**/__tests__",
"./src/**/__mocks__",
"./src/**/__fixtures__",
"node_modules"
]
}
@@ -0,0 +1,5 @@
{
"extends": "./tsconfig.json",
"include": ["src"],
"exclude": ["dist", "node_modules"]
}
+155 -12
View File
@@ -6068,6 +6068,44 @@ __metadata:
languageName: unknown
linkType: soft
"@medusajs/medusa-cli@npm:1.3.12":
version: 1.3.12
resolution: "@medusajs/medusa-cli@npm:1.3.12"
dependencies:
"@medusajs/utils": 1.8.3
axios: ^0.21.4
chalk: ^4.0.0
configstore: 5.0.1
core-js: ^3.6.5
dotenv: ^8.2.0
execa: ^5.1.1
fs-exists-cached: ^1.0.0
fs-extra: ^10.0.0
hosted-git-info: ^4.0.2
inquirer: ^8.0.0
is-valid-path: ^0.1.1
meant: ^1.0.3
medusa-core-utils: ^1.2.0
medusa-telemetry: 0.0.16
open: ^8.0.6
ora: ^5.4.1
pg-god: ^1.0.12
prompts: ^2.4.2
regenerator-runtime: ^0.13.11
resolve-cwd: ^3.0.0
semver: ^7.3.8
sqlite3: ^5.0.2
stack-trace: ^0.0.10
ulid: ^2.3.0
url: ^0.11.0
winston: ^3.8.2
yargs: ^15.3.1
bin:
medusa: cli.js
checksum: ec37a946fce88023917d78883d9525f7a9580df110be1d4e1671e0332f8507d0443d697af13896110df90e78fc8f6300e05881364d1f01cdb4692b0c61ad5074
languageName: node
linkType: hard
"@medusajs/medusa-cli@npm:1.3.13":
version: 1.3.13
resolution: "@medusajs/medusa-cli@npm:1.3.13"
@@ -6222,6 +6260,68 @@ __metadata:
languageName: unknown
linkType: soft
"@medusajs/medusa@npm:1.10.0":
version: 1.10.0
resolution: "@medusajs/medusa@npm:1.10.0"
dependencies:
"@medusajs/medusa-cli": 1.3.12
"@medusajs/modules-sdk": 1.8.4
"@medusajs/utils": 1.8.3
"@types/ioredis": ^4.28.10
"@types/lodash": ^4.14.191
awilix: ^8.0.0
body-parser: ^1.19.0
boxen: ^5.0.1
bullmq: ^3.5.6
chokidar: ^3.4.2
class-transformer: ^0.5.1
class-validator: ^0.14.0
compression: ^1.7.4
connect-redis: ^5.0.0
cookie-parser: ^1.4.6
core-js: ^3.6.5
cors: ^2.8.5
cross-spawn: ^7.0.3
dotenv: ^16.0.3
express: ^4.18.2
express-session: ^1.17.3
fs-exists-cached: ^1.0.0
glob: ^7.1.6
ioredis: ^5.2.5
ioredis-mock: 8.4.0
iso8601-duration: ^1.3.0
jsonwebtoken: ^9.0.0
lodash: ^4.17.21
medusa-core-utils: ^1.2.0
medusa-telemetry: ^0.0.16
medusa-test-utils: ^1.1.40
morgan: ^1.9.1
multer: ^1.4.5-lts.1
node-schedule: ^2.1.1
papaparse: ^5.3.2
passport: ^0.6.0
passport-http-bearer: ^1.0.1
passport-jwt: ^4.0.1
passport-local: ^1.0.0
randomatic: ^3.1.1
redis: ^3.0.2
reflect-metadata: ^0.1.13
regenerator-runtime: ^0.13.11
request-ip: ^2.1.3
scrypt-kdf: ^2.0.1
ulid: ^2.3.0
uuid: ^9.0.0
winston: ^3.8.2
peerDependencies:
"@medusajs/types": 1.8.4
medusa-interfaces: 1.3.7
typeorm: "*"
bin:
medusa: cli.js
checksum: ef7a2e9789daa407777ed5e149470878575df729279a83828005ada7f8a7704e7f82816cb225d4e03327e6ed8982d0a7e4a0f674155ee6bc4a7f2ecef57216db
languageName: node
linkType: hard
"@medusajs/medusa@npm:1.10.1":
version: 1.10.1
resolution: "@medusajs/medusa@npm:1.10.1"
@@ -6301,6 +6401,20 @@ __metadata:
languageName: unknown
linkType: soft
"@medusajs/modules-sdk@npm:1.8.4":
version: 1.8.4
resolution: "@medusajs/modules-sdk@npm:1.8.4"
dependencies:
"@medusajs/types": 1.8.4
"@medusajs/utils": 1.8.3
awilix: ^8.0.0
glob: 7.1.6
medusa-telemetry: ^0.0.16
resolve-cwd: ^3.0.0
checksum: f77f9396708c076b7062ab03171183d27b0cad849fc1daa2d67ef88713b3a437665bc083c1f1b791671899ced11fbaa889459f34b72280c4b9099570dd051a8e
languageName: node
linkType: hard
"@medusajs/modules-sdk@npm:1.8.5":
version: 1.8.5
resolution: "@medusajs/modules-sdk@npm:1.8.5"
@@ -6389,6 +6503,13 @@ __metadata:
languageName: unknown
linkType: soft
"@medusajs/types@npm:1.8.4":
version: 1.8.4
resolution: "@medusajs/types@npm:1.8.4"
checksum: bbf94191331da4b97eea390f54b86909d0e2d6c20098b829586897e57a9d1e32ba6d3c09554b596f7d134106fe96cd8d29ac008281f2d796bb6182a13e19bfed
languageName: node
linkType: hard
"@medusajs/types@npm:1.8.5":
version: 1.8.5
resolution: "@medusajs/types@npm:1.8.5"
@@ -6414,6 +6535,19 @@ __metadata:
languageName: unknown
linkType: soft
"@medusajs/utils@npm:1.8.3":
version: 1.8.3
resolution: "@medusajs/utils@npm:1.8.3"
dependencies:
awilix: ^8.0.0
class-transformer: ^0.5.1
class-validator: ^0.13.2
typeorm: "npm:@medusajs/typeorm@0.3.16-next.0"
ulid: ^2.3.0
checksum: 90a980570ef9a55c70eeaff3af7ab3518beef28f3b955279dfed7d45eb93bd7ceb0ae3d70d44f9c14cc871072db61d382505cd4c7dc6b020b729ceabecf5e23c
languageName: node
linkType: hard
"@medusajs/utils@npm:1.8.4":
version: 1.8.4
resolution: "@medusajs/utils@npm:1.8.4"
@@ -16200,6 +16334,16 @@ __metadata:
languageName: node
linkType: hard
"class-validator@npm:^0.13.2":
version: 0.13.2
resolution: "class-validator@npm:0.13.2"
dependencies:
libphonenumber-js: ^1.9.43
validator: ^13.7.0
checksum: e7a1a318967229582b25da9c3b81e316627b014640968824b00bf001f4d79101017b91c59cb3f2c8c0922c4446b5a1114c27ba91aae1c1f109e0ad4d504dfcd5
languageName: node
linkType: hard
"class-validator@npm:^0.14.0":
version: 0.14.0
resolution: "class-validator@npm:0.14.0"
@@ -28117,6 +28261,13 @@ __metadata:
languageName: node
linkType: hard
"libphonenumber-js@npm:^1.9.43":
version: 1.10.30
resolution: "libphonenumber-js@npm:1.10.30"
checksum: 9aa86196ad1db6cdbe792e963edf38518d731945f590b65125aff5f0d84d4cef9a1258f9d0b3ffa7698a30f4e67fc557b4e375b74e34e85d98bfb4740b8f342e
languageName: node
linkType: hard
"lilconfig@npm:^2.0.3, lilconfig@npm:^2.0.5, lilconfig@npm:^2.0.6":
version: 2.0.6
resolution: "lilconfig@npm:2.0.6"
@@ -29696,16 +29847,8 @@ __metadata:
version: 0.0.0-use.local
resolution: "medusa-plugin-mailchimp@workspace:packages/medusa-plugin-mailchimp"
dependencies:
"@babel/cli": ^7.7.5
"@babel/core": ^7.7.5
"@babel/node": ^7.7.4
"@babel/plugin-proposal-class-properties": ^7.7.4
"@babel/plugin-transform-classes": ^7.9.5
"@babel/plugin-transform-instanceof": ^7.8.3
"@babel/plugin-transform-runtime": ^7.7.6
"@babel/preset-env": ^7.7.5
"@babel/register": ^7.7.4
"@babel/runtime": ^7.9.6
"@medusajs/medusa": 1.10.0
"@types/express": ^4.17.17
body-parser: ^1.19.0
client-sessions: ^0.8.0
cors: ^2.8.5
@@ -29714,10 +29857,10 @@ __metadata:
jest: ^25.5.4
mailchimp-api-v3: ^1.14.0
medusa-core-utils: ^1.2.0
medusa-interfaces: ^1.3.7
medusa-test-utils: ^1.1.40
typescript: ^4.4.4
peerDependencies:
medusa-interfaces: 1.3.7
"@medusajs/medusa": 1.10.0
languageName: unknown
linkType: soft