fix(medusa): Remove deps mongoose + mongodb (#1218)

* fix(medusa): Remove deps mongoose, mongodb and transaction service + base model

* chore: delete permissions+add-ons legacy plugins

Co-authored-by: Sebastian Rindom <skrindom@gmail.com>
This commit is contained in:
Oliver Windall Juhl
2022-07-04 09:10:32 +02:00
committed by GitHub
co-authored by Sebastian Rindom
parent 8fe5fb5503
commit c76e23e84d
52 changed files with 28 additions and 9053 deletions
@@ -1,153 +0,0 @@
import mongoose from "mongoose"
/**
* Interface for data models. The default data layer uses an internal mongoose
* model and is as such compatible with MongoDB.
* @interface
*/
class BaseModel {
constructor() {
/** @const the underlying mongoose model used for queries */
this.mongooseModel_ = this.createMongooseModel_()
}
/**
* Returns the model schema. The child class must implement the static schema
* property.
* @return {string} the models schema
*/
getSchema() {
if (!this.constructor.schema) {
throw new Error("Schema not defined")
}
return this.constructor.schema
}
/**
* Returns the model name. The child class must implement the static modelName
* property.
* @return {string} the name of the model
*/
getModelName() {
if (!this.constructor.modelName) {
throw new Error("Every model must have a static modelName property")
}
return this.constructor.modelName
}
/**
* Returns the schema options defined in child class.
* @return {object} the schema options
*/
getSchemaOptions() {
if (!this.constructor.schemaOptions) {
return {}
}
return this.constructor.schemaOptions
}
/**
* @private
* Creates a mongoose model based on schema, schema options and model name.
* @return {Mongooose.Model} the mongoose model
*/
createMongooseModel_() {
const schema = this.getSchema()
const options = this.getSchemaOptions()
const mongooseSchema = new mongoose.Schema(schema, options)
return mongoose.model(this.getModelName(), mongooseSchema)
}
/**
*/
startSession() {
return this.mongooseModel_.startSession()
}
/**
* Queries the mongoose model via the mongoose's findOne.
* @param query {object} a mongoose selector query
* @param options {?object=} mongoose options
* @return {?mongoose.Document} the retreived mongoose document or null.
*/
findOne(query, options = {}) {
return this.mongooseModel_.findOne(query, options).lean()
}
/**
* Queries the mongoose model via the mongoose's find.
* @param query {object} a mongoose selector query
* @param options {?object=} mongoose options
* @return {Array<mongoose.Document>} the retreived mongoose documents or
* an empty array
*/
find(query, options, offset, limit) {
return this.mongooseModel_
.find(query, options)
.skip(offset)
.limit(limit)
.lean()
}
count() {
return this.mongooseModel_.count({})
}
/**
* Update a model via the mongoose model's updateOne.
* @param query {object} a mongoose selector query
* @param update {object} mongoose update object
* @param options {?object=} mongoose options
* @return {object} mongoose result
*/
updateOne(query, update, options = {}) {
options.new = true
return this.mongooseModel_.findOneAndUpdate(query, update, options).lean()
}
/**
* Update a model via the mongoose model's update.
* @param query {object} a mongoose selector query
* @param update {object} mongoose update object
* @param options {?object=} mongoose options
* @return {object} mongoose result
*/
update(query, update, options) {
return this.mongooseModel_.update(query, update, options)
}
/**
* Creates a document in the mongoose model's collection via create.
* @param object {object} the value of the document to be created
* @param options {?object=} mongoose options
* @return {object} mongoose result
*/
create(object, options) {
return this.mongooseModel_.create(object, options)
}
/**
* Deletes a document in the mongoose model's collection
* @param query {object} the value of the document to be created
* @param options {?object=} mongoose options
* @return {object} mongoose result
*/
deleteOne(query, options) {
return this.mongooseModel_.deleteOne(query, options)
}
/**
* Deletes many document in the mongoose model's collection
* @param query {object} the value of the document to be created
* @param options {?object=} mongoose options
* @return {object} mongoose result
*/
delete(query, options) {
return this.mongooseModel_.deleteMany(query, options)
}
}
export default BaseModel
+2 -3
View File
@@ -1,8 +1,7 @@
export { default as BaseService } from "./base-service"
export { default as BaseModel } from "./base-model"
export { default as PaymentService } from "./payment-service"
export { default as FulfillmentService } from "./fulfillment-service"
export { default as FileService } from "./file-service"
export { default as FulfillmentService } from "./fulfillment-service"
export { default as NotificationService } from "./notification-service"
export { default as OauthService } from "./oauth-service"
export { default as PaymentService } from "./payment-service"
export { default as SearchService } from "./search-service"
-13
View File
@@ -1,13 +0,0 @@
{
"plugins": [
"@babel/plugin-proposal-class-properties",
"@babel/plugin-transform-instanceof",
"@babel/plugin-transform-classes"
],
"presets": ["@babel/preset-env"],
"env": {
"test": {
"plugins": ["@babel/plugin-transform-runtime"]
}
}
}
-15
View File
@@ -1,15 +0,0 @@
/lib
node_modules
.DS_store
.env*
/*.js
!index.js
/dist
/api
/services
/models
/subscribers
/loaders
@@ -1,8 +0,0 @@
/lib
node_modules
.DS_store
.env*
/*.js
!index.js
yarn.lock
/src
-222
View File
@@ -1,222 +0,0 @@
# Change Log
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
# [1.2.0](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.37...medusa-plugin-add-ons@1.2.0) (2022-05-01)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.1.37](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.36...medusa-plugin-add-ons@1.1.37) (2022-01-11)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.1.36](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.35...medusa-plugin-add-ons@1.1.36) (2021-12-29)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.1.35](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.34...medusa-plugin-add-ons@1.1.35) (2021-12-17)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.1.34](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.33...medusa-plugin-add-ons@1.1.34) (2021-12-08)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.1.33](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.32...medusa-plugin-add-ons@1.1.33) (2021-11-23)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.1.32](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.31...medusa-plugin-add-ons@1.1.32) (2021-11-22)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.1.31](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.30...medusa-plugin-add-ons@1.1.31) (2021-11-19)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.1.30](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.29...medusa-plugin-add-ons@1.1.30) (2021-11-19)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.1.29](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.28...medusa-plugin-add-ons@1.1.29) (2021-10-18)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.1.28](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.27...medusa-plugin-add-ons@1.1.28) (2021-10-18)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.1.27](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.25...medusa-plugin-add-ons@1.1.27) (2021-10-18)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.1.26](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.25...medusa-plugin-add-ons@1.1.26) (2021-10-18)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.1.25](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.24...medusa-plugin-add-ons@1.1.25) (2021-09-15)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.1.24](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.23...medusa-plugin-add-ons@1.1.24) (2021-09-14)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.1.23](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.22...medusa-plugin-add-ons@1.1.23) (2021-08-05)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.1.22](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.21...medusa-plugin-add-ons@1.1.22) (2021-07-26)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.1.21](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.19...medusa-plugin-add-ons@1.1.21) (2021-07-15)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.1.20](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.19...medusa-plugin-add-ons@1.1.20) (2021-07-15)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.1.19](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.18...medusa-plugin-add-ons@1.1.19) (2021-07-02)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.1.18](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.17...medusa-plugin-add-ons@1.1.18) (2021-06-22)
### Bug Fixes
- release assist ([668e8a7](https://github.com/medusajs/medusa/commit/668e8a740200847fc2a41c91d2979097f1392532))
## [1.1.17](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.16...medusa-plugin-add-ons@1.1.17) (2021-06-09)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.1.16](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.15...medusa-plugin-add-ons@1.1.16) (2021-06-09)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.1.15](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.14...medusa-plugin-add-ons@1.1.15) (2021-06-09)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.1.14](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.13...medusa-plugin-add-ons@1.1.14) (2021-06-09)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.1.13](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.12...medusa-plugin-add-ons@1.1.13) (2021-06-08)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.1.12](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.9...medusa-plugin-add-ons@1.1.12) (2021-04-28)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.1.11](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.10...medusa-plugin-add-ons@1.1.11) (2021-04-20)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.1.10](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.9...medusa-plugin-add-ons@1.1.10) (2021-04-20)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.1.9](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.8...medusa-plugin-add-ons@1.1.9) (2021-04-13)
### Bug Fixes
- merge develop ([2982a8e](https://github.com/medusajs/medusa/commit/2982a8e682e90beb4549d969d9d3b04d78a46a2d))
- merge develop ([a468c45](https://github.com/medusajs/medusa/commit/a468c451e82c68f41b5005a2e480057f6124aaa6))
## [1.1.8](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.7...medusa-plugin-add-ons@1.1.8) (2021-04-13)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.1.7](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.6...medusa-plugin-add-ons@1.1.7) (2021-03-30)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.1.6](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.5...medusa-plugin-add-ons@1.1.6) (2021-03-17)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.1.5](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.3...medusa-plugin-add-ons@1.1.5) (2021-03-17)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.1.4](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.3...medusa-plugin-add-ons@1.1.4) (2021-03-17)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.1.3](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.2...medusa-plugin-add-ons@1.1.3) (2021-02-17)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.1.2](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.1...medusa-plugin-add-ons@1.1.2) (2021-02-03)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.1.1](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.1.0...medusa-plugin-add-ons@1.1.1) (2021-01-27)
**Note:** Version bump only for package medusa-plugin-add-ons
# [1.1.0](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.0.8...medusa-plugin-add-ons@1.1.0) (2021-01-26)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.0.8](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.0.7...medusa-plugin-add-ons@1.0.8) (2020-12-17)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.0.7](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.0.6...medusa-plugin-add-ons@1.0.7) (2020-11-24)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.0.6](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.0.5...medusa-plugin-add-ons@1.0.6) (2020-10-19)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.0.5](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.0.4...medusa-plugin-add-ons@1.0.5) (2020-10-12)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.0.4](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.0.3...medusa-plugin-add-ons@1.0.4) (2020-10-09)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.0.3](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.0.2...medusa-plugin-add-ons@1.0.3) (2020-10-05)
### Bug Fixes
- **medusa-plugin-add-ons:** fixes add-on decorator ([5071f36](https://github.com/medusajs/medusa/commit/5071f362e4e140d11a1342a5058e8ad2efaa1ed4))
- **medusa-plugin-addon:** Fixes admin endpoints, Adds flag to avoid merging add-on line-items ([d8483cd](https://github.com/medusajs/medusa/commit/d8483cd1352ecc587112723786b7c31882f9416e))
## [1.0.2](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.0.1...medusa-plugin-add-ons@1.0.2) (2020-09-09)
**Note:** Version bump only for package medusa-plugin-add-ons
## [1.0.1](https://github.com/medusajs/medusa/compare/medusa-plugin-add-ons@1.0.0...medusa-plugin-add-ons@1.0.1) (2020-09-09)
**Note:** Version bump only for package medusa-plugin-add-ons
# 1.0.0 (2020-09-09)
### Features
- **plugins:** Adds add-on plugin ([3de1e6d](https://github.com/medusajs/medusa/commit/3de1e6dd4ad4a2a48d4d8116ebdd011efce2b22a))
-1
View File
@@ -1 +0,0 @@
// noop
@@ -1,44 +0,0 @@
{
"name": "medusa-plugin-add-ons",
"version": "1.2.0",
"description": "Add-on plugin for Medusa Commerce",
"main": "index.js",
"repository": {
"type": "git",
"url": "https://github.com/medusajs/medusa",
"directory": "packages/medusa-plugin-add-ons"
},
"author": "Oliver Juhl",
"license": "AGPL-3.0-or-later",
"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-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",
"client-sessions": "^0.8.0",
"cross-env": "^7.0.2",
"eslint": "^6.8.0",
"jest": "^25.5.2",
"medusa-test-utils": "^1.1.37"
},
"scripts": {
"build": "babel src -d . --ignore **/__tests__",
"prepare": "cross-env NODE_ENV=production npm run build",
"watch": "babel -w src --out-dir . --ignore **/__tests__",
"test": "jest"
},
"dependencies": {
"body-parser": "^1.19.0",
"cors": "^2.8.5",
"express": "^4.17.1",
"medusa-core-utils": "^1.1.31",
"redis": "^3.0.2"
},
"gitHead": "81a7ff73d012fda722f6e9ef0bd9ba0232d37808"
}
@@ -1,12 +0,0 @@
import { Router } from "express"
import admin from "./routes/admin"
import store from "./routes/store"
export default (rootDirectory) => {
const app = Router()
store(app, rootDirectory)
admin(app, rootDirectory)
return app
}
@@ -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,29 +0,0 @@
import { Validator, MedusaError } from "medusa-core-utils"
export default async (req, res) => {
const schema = Validator.object().keys({
name: Validator.string().required(),
prices: Validator.array()
.items({
currency_code: Validator.string(),
amount: Validator.number(),
})
.required(),
valid_for: Validator.array().items(),
metadata: Validator.object().optional(),
})
const { value, error } = schema.validate(req.body)
if (error) {
throw new MedusaError(MedusaError.Types.INVALID_DATA, error.details)
}
try {
const addOnService = req.scope.resolve("addOnService")
const addOn = await addOnService.create(value)
res.status(200).json({ addOn })
} catch (err) {
throw err
}
}
@@ -1,16 +0,0 @@
export default async (req, res) => {
const { id } = req.params
const addOnService = req.scope.resolve("addOnService")
try {
await addOnService.delete(id)
res.status(200).send({
id,
object: "addOn",
deleted: true,
})
} catch (err) {
throw err
}
}
@@ -1,17 +0,0 @@
export default async (req, res) => {
const { id } = req.params
try {
const addOnService = req.scope.resolve("addOnService")
let addOn = await addOnService.retrieve(id)
addOn = await addOnService.decorate(
addOn,
["name", "valid_for", "prices"],
["valid_for"]
)
res.json({ add_on: addOn })
} catch (err) {
throw err
}
}
@@ -1,55 +0,0 @@
import { Router } from "express"
import bodyParser from "body-parser"
import cors from "cors"
import middlewares from "../../middlewares"
import { getConfigFile } from "medusa-core-utils"
const route = Router()
export default (app, rootDirectory) => {
const { configModule } = getConfigFile(rootDirectory, `medusa-config`)
const config = (configModule && configModule.projectConfig) || {}
const adminCors = config.admin_cors || ""
route.use(
cors({
origin: adminCors.split(","),
credentials: true,
})
)
app.use("/admin", route)
route.post(
"/add-ons",
bodyParser.json(),
middlewares.wrap(require("./create-add-on").default)
)
route.post(
"/add-ons/:id",
bodyParser.json(),
middlewares.wrap(require("./update-add-on").default)
)
route.get(
"/add-ons",
bodyParser.json(),
middlewares.wrap(require("./list-add-ons").default)
)
route.get(
"/add-ons/:id",
bodyParser.json(),
middlewares.wrap(require("./get-add-on").default)
)
route.delete(
"/add-ons/:id",
bodyParser.json(),
middlewares.wrap(require("./delete-add-on").default)
)
return app
}
@@ -1,20 +0,0 @@
export default async (req, res) => {
try {
const addOnService = req.scope.resolve("addOnService")
let addOns = await addOnService.list({})
addOns = await Promise.all(
addOns.map((ao) =>
addOnService.decorate(
ao,
["name", "valid_for", "prices"],
["valid_for"]
)
)
)
res.status(200).json({ add_ons: addOns })
} catch (err) {
console.log(err)
throw err
}
}
@@ -1,39 +0,0 @@
import { Validator, MedusaError } from "medusa-core-utils"
export default async (req, res) => {
const { id } = req.params
const schema = Validator.object().keys({
name: Validator.string().optional(),
prices: Validator.array()
.items({
currency_code: Validator.string().required(),
amount: Validator.number().required(),
})
.optional(),
valid_for: Validator.array().optional(),
metadata: Validator.object().optional(),
})
const { value, error } = schema.validate(req.body)
if (error) {
throw new MedusaError(MedusaError.Types.INVALID_DATA, error.details)
}
try {
const addOnService = req.scope.resolve("addOnService")
if (value.metadata) {
Object.entries(value.metadata).map(([key, value]) => {
addOnService.setMetadata(id, key, value)
})
delete value.metadata
}
const addOn = await addOnService.update(id, value)
res.status(200).json({ addOn })
} catch (err) {
throw err
}
}
@@ -1,39 +0,0 @@
import { Validator, MedusaError } from "medusa-core-utils"
export default async (req, res) => {
const { id } = req.params
const schema = Validator.object().keys({
variant_id: Validator.string().required(),
quantity: Validator.number().required(),
add_ons: Validator.array().items(Validator.string()).optional(),
metadata: Validator.object().optional(),
})
const { value, error } = schema.validate(req.body)
if (error) {
throw new MedusaError(MedusaError.Types.INVALID_DATA, error.details)
}
try {
const lineItemService = req.scope.resolve("addOnLineItemService")
const cartService = req.scope.resolve("cartService")
let cart = await cartService.retrieve(id)
const lineItem = await lineItemService.generate(
value.variant_id,
cart.region_id,
value.quantity,
value.add_ons,
value.metadata
)
cart = await cartService.addLineItem(cart._id, lineItem)
cart = await cartService.decorate(cart, [], ["region"])
res.status(200).json({ cart })
} catch (err) {
throw err
}
}
@@ -1,27 +0,0 @@
import { Validator } from "medusa-core-utils"
export default async (req, res) => {
const schema = Validator.object({
product_id: Validator.string().required(),
})
const { value, error } = schema.validate(region_id)
if (error) {
throw error
}
try {
const addOnService = req.scope.resolve("addOnService")
let addOn = await addOnService.retrieveByProduct(value.product_id)
addOn = await addOnService.decorate(
addOn,
["name", "valid_for", "prices"],
["valid_for"]
)
res.json({ add_on: addOn })
} catch (err) {
throw err
}
}
@@ -1,37 +0,0 @@
import { Router } from "express"
import bodyParser from "body-parser"
import cors from "cors"
import middlewares from "../../middlewares"
import { getConfigFile } from "medusa-core-utils"
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: storeCors.split(","),
credentials: true,
})
)
app.use("/store", route)
route.post(
"/carts/:id/line-items/add-on",
bodyParser.json(),
middlewares.wrap(require("./create-line-item").default)
)
route.post(
"/carts/:id/line-items/:line_id/add-on",
bodyParser.json(),
middlewares.wrap(require("./update-line-item").default)
)
return app
}
@@ -1,52 +0,0 @@
import { Validator, MedusaError } from "medusa-core-utils"
export default async (req, res) => {
const { id, line_id } = req.params
const schema = Validator.object().keys({
add_ons: Validator.array().items(Validator.string()).optional(),
quantity: Validator.number().optional(),
metadata: Validator.object().optional(),
})
const { value, error } = schema.validate(req.body)
if (error) {
throw new MedusaError(MedusaError.Types.INVALID_DATA, error.details)
}
try {
const lineItemService = req.scope.resolve("addOnLineItemService")
const cartService = req.scope.resolve("cartService")
let cart
if (value.quantity === 0) {
cart = await cartService.removeLineItem(id, line_id)
} else {
cart = await cartService.retrieve(id)
const existing = cart.items.find((i) => i._id.equals(line_id))
if (!existing) {
throw new MedusaError(
MedusaError.Types.INVALID_DATA,
"Could not find the line item"
)
}
const lineItem = await lineItemService.generate(
existing.content.variant._id,
cart.region_id,
value.quantity,
value.add_ons,
value.metadata
)
cart = await cartService.updateLineItem(cart._id, line_id, lineItem)
}
cart = await cartService.decorate(cart, [], ["region"])
res.status(200).json({ cart })
} catch (err) {
throw err
}
}
@@ -1,26 +0,0 @@
export default (container, config) => {
const cartService = container.resolve("cartService")
const addOnLineItemService = container.resolve("addOnLineItemService")
cartService.addDecorator(async (cart) => {
try {
cart.items = await Promise.all(
cart.items.map((item) => {
if (item.metadata && item.metadata.add_ons) {
return addOnLineItemService.decorate(
item,
["title", "quantity", "thumbnail", "content", "should_merge"],
["add_ons"]
)
} else {
return item
}
})
)
return cart
} catch (error) {
return cart
}
})
}
@@ -1,46 +0,0 @@
import { IdMap } from "medusa-test-utils"
export const addOns = {
testAddOn: {
_id: IdMap.getId("test-add-on"),
name: "Chili",
prices: [
{
currency_code: "DKK",
amount: 20,
},
],
valid_for: [IdMap.getId("test-product")],
},
testAddOn2: {
_id: IdMap.getId("test-add-on-2"),
name: "Chili",
prices: [
{
currency_code: "DKK",
amount: 20,
},
],
valid_for: [IdMap.getId("test-product")],
},
}
export const AddOnModelMock = {
create: jest.fn().mockReturnValue(Promise.resolve()),
find: jest.fn().mockImplementation((query) => {
return Promise.resolve([addOns.testAddOn, addOns.testAddOn2])
}),
updateOne: jest.fn().mockImplementation((query, update) => {
return Promise.resolve()
}),
deleteOne: jest.fn().mockReturnValue(Promise.resolve()),
findOne: jest.fn().mockImplementation((query) => {
if (query._id === IdMap.getId("test-add-on")) {
return Promise.resolve(addOns.testAddOn)
}
if (query._id === IdMap.getId("test-add-on-2")) {
return Promise.resolve(addOns.testAddOn2)
}
return Promise.resolve(undefined)
}),
}
@@ -1,15 +0,0 @@
import mongoose from "mongoose"
import { BaseModel } from "medusa-interfaces"
class AddOnModel extends BaseModel {
static modelName = "AddOn"
static schema = {
name: { type: String, required: true },
prices: { type: [], required: true },
// Valid products
valid_for: { type: [String], required: true },
metadata: { type: mongoose.Schema.Types.Mixed, default: {} },
}
}
export default AddOnModel
@@ -1,70 +0,0 @@
import { IdMap } from "medusa-test-utils"
export const addOns = {
testAddOn: {
_id: IdMap.getId("test-add-on"),
name: "Chili",
prices: [
{
currency_code: "DKK",
amount: 20,
},
],
valid_for: [IdMap.getId("test-product")],
},
testAddOn2: {
_id: IdMap.getId("test-add-on-2"),
name: "Chili",
prices: [
{
currency_code: "DKK",
amount: 20,
},
],
valid_for: [IdMap.getId("test-product")],
},
testAddOn3: {
_id: IdMap.getId("test-add-on-3"),
name: "Herbs",
prices: [
{
currency_code: "DKK",
amount: 20,
},
],
valid_for: [],
},
}
export const AddOnServiceMock = {
retrieve: jest.fn().mockImplementation((addOnId) => {
if (addOnId === IdMap.getId("test-add-on")) {
return Promise.resolve(addOns.testAddOn)
}
if (addOnId === IdMap.getId("test-add-on-2")) {
return Promise.resolve(addOns.testAddOn2)
}
if (addOnId === IdMap.getId("test-add-on-3")) {
return Promise.resolve(addOns.testAddOn3)
}
return Promise.resolve(undefined)
}),
getRegionPrice: jest.fn().mockImplementation((addOnId, regionId) => {
if (addOnId === IdMap.getId("test-add-on")) {
return Promise.resolve(20)
}
if (addOnId === IdMap.getId("test-add-on-2")) {
return Promise.resolve(20)
}
if (addOnId === IdMap.getId("test-add-on-3")) {
return Promise.resolve(20)
}
return Promise.resolve(undefined)
}),
}
const mock = jest.fn().mockImplementation(() => {
return AddOnServiceMock
})
export default mock
@@ -1,10 +0,0 @@
export const EventBusServiceMock = {
emit: jest.fn(),
subscribe: jest.fn(),
}
const mock = jest.fn().mockImplementation(() => {
return EventBusServiceMock
})
export default mock
@@ -1,94 +0,0 @@
import { IdMap } from "medusa-test-utils"
const variant1 = {
_id: IdMap.getId("test-variant-1"),
title: "variant1",
options: [],
}
const variant2 = {
_id: IdMap.getId("test-variant-2"),
title: "variant2",
options: [
{
option_id: IdMap.getId("color_id"),
value: "black",
},
{
option_id: IdMap.getId("size_id"),
value: "160",
},
],
}
const variant3 = {
_id: IdMap.getId("test-variant-3"),
title: "variant3",
options: [
{
option_id: IdMap.getId("color_id"),
value: "blue",
},
{
option_id: IdMap.getId("size_id"),
value: "150",
},
],
}
const variant4 = {
_id: IdMap.getId("test-variant-4"),
title: "variant4",
options: [
{
option_id: IdMap.getId("color_id"),
value: "blue",
},
{
option_id: IdMap.getId("size_id"),
value: "50",
},
],
}
export const variants = {
one: variant1,
two: variant2,
three: variant3,
four: variant4,
}
export const ProductVariantServiceMock = {
retrieve: jest.fn().mockImplementation((variantId) => {
if (variantId === IdMap.getId("test-variant-1")) {
return Promise.resolve(variant1)
}
if (variantId === IdMap.getId("test-variant-2")) {
return Promise.resolve(variant2)
}
if (variantId === IdMap.getId("test-variant-3")) {
return Promise.resolve(variant3)
}
if (variantId === IdMap.getId("test-variant-4")) {
return Promise.resolve(variant4)
}
return Promise.resolve(undefined)
}),
getRegionPrice: jest.fn().mockImplementation((variantId, context) => {
if (variantId === IdMap.getId("test-variant-1")) {
if (context.regionId === IdMap.getId("world")) {
return Promise.resolve(10)
} else {
return Promise.resolve(20)
}
}
return Promise.reject(new Error("Not found"))
}),
}
const mock = jest.fn().mockImplementation(() => {
return ProductVariantServiceMock
})
export default mock
@@ -1,39 +0,0 @@
import { IdMap } from "medusa-test-utils"
export const products = {
product1: {
_id: IdMap.getId("test-product"),
description: "Test description",
title: "Product 1",
variants: [IdMap.getId("test-variant-1")],
// metadata: {
// add_ons: [IdMap.getId("test-add-on"), IdMap.getId("test-add-on-2")],
// },
},
product2: {
_id: IdMap.getId("test-product-2"),
title: "Product 2",
metadata: {},
},
}
export const ProductServiceMock = {
retrieve: jest.fn().mockImplementation((productId) => {
if (productId === IdMap.getId("test-product")) {
return Promise.resolve(products.product1)
}
if (productId === IdMap.getId("test-product-2")) {
return Promise.resolve(products.product2)
}
return Promise.resolve(undefined)
}),
list: jest.fn().mockImplementation((query) => {
return Promise.resolve([products.product1])
}),
}
const mock = jest.fn().mockImplementation(() => {
return ProductServiceMock
})
export default mock
@@ -1,28 +0,0 @@
import { IdMap } from "medusa-test-utils"
export const regions = {
testRegion: {
_id: IdMap.getId("world"),
name: "Test Region",
countries: ["DK", "US", "DE"],
tax_rate: 0.25,
payment_providers: ["default_provider", "unregistered"],
fulfillment_providers: ["test_shipper"],
currency_code: "DKK",
},
}
export const RegionServiceMock = {
retrieve: jest.fn().mockImplementation((regionId) => {
if (regionId === IdMap.getId("world")) {
return Promise.resolve(regions.testRegion)
}
throw Error(regionId + "not found")
}),
}
const mock = jest.fn().mockImplementation(() => {
return RegionServiceMock
})
export default mock
@@ -1,106 +0,0 @@
import { IdMap } from "medusa-test-utils"
import AddOnLineItemService from "../add-on-line-item"
import { ProductVariantServiceMock } from "../__mocks__/product-variant"
import { ProductServiceMock } from "../__mocks__/product"
import { RegionServiceMock } from "../__mocks__/region"
import { AddOnServiceMock } from "../__mocks__/add-on"
describe("LineItemService", () => {
describe("generate", () => {
let result
const lineItemService = new AddOnLineItemService({
addOnService: AddOnServiceMock,
productVariantService: ProductVariantServiceMock,
productService: ProductServiceMock,
regionService: RegionServiceMock,
})
beforeAll(async () => {
jest.clearAllMocks()
})
it("generates line item and successfully calculates full unit_price", async () => {
result = await lineItemService.generate(
IdMap.getId("test-variant-1"),
IdMap.getId("world"),
1,
[IdMap.getId("test-add-on"), IdMap.getId("test-add-on-2")]
)
expect(result).toEqual({
title: "Product 1",
thumbnail: undefined,
should_merge: false,
content: {
unit_price: 50,
variant: {
_id: IdMap.getId("test-variant-1"),
title: "variant1",
options: [],
},
product: {
_id: IdMap.getId("test-product"),
description: "Test description",
title: "Product 1",
variants: [IdMap.getId("test-variant-1")],
},
quantity: 1,
},
metadata: {
add_ons: [IdMap.getId("test-add-on"), IdMap.getId("test-add-on-2")],
},
quantity: 1,
})
})
it("generates line item and successfully calculates full unit_price for large quantity", async () => {
result = await lineItemService.generate(
IdMap.getId("test-variant-1"),
IdMap.getId("world"),
3,
[IdMap.getId("test-add-on"), IdMap.getId("test-add-on-2")]
)
expect(result).toEqual({
title: "Product 1",
thumbnail: undefined,
should_merge: false,
content: {
unit_price: 150,
variant: {
_id: IdMap.getId("test-variant-1"),
title: "variant1",
options: [],
},
product: {
_id: IdMap.getId("test-product"),
description: "Test description",
title: "Product 1",
variants: [IdMap.getId("test-variant-1")],
},
quantity: 1,
},
metadata: {
add_ons: [IdMap.getId("test-add-on"), IdMap.getId("test-add-on-2")],
},
quantity: 3,
})
})
it("fails if variant has no associated product", async () => {
try {
await lineItemService.generate(
IdMap.getId("test-variant-1"),
IdMap.getId("world"),
1,
[
IdMap.getId("test-add-on"),
IdMap.getId("test-add-on-2"),
IdMap.getId("test-add-on-3"),
]
)
} catch (err) {
expect(err.message).toBe(`Herbs can not be added to Product 1`)
}
})
})
})
@@ -1,134 +0,0 @@
import { IdMap } from "medusa-test-utils"
import { AddOnModelMock, addOns } from "../../models/__mocks__/add-on"
import AddOnService from "../add-on"
import { EventBusServiceMock } from "../__mocks__/event-bus"
import { ProductServiceMock } from "../__mocks__/product"
describe("AddOnService", () => {
describe("create", () => {
const addOnService = new AddOnService({
addOnModel: AddOnModelMock,
productService: ProductServiceMock,
eventBusService: EventBusServiceMock,
})
beforeEach(async () => {
jest.clearAllMocks()
})
it("calls model layer create", async () => {
await addOnService.create({
name: "Chili",
prices: [
{
currency_code: "DKK",
amount: 20,
},
],
valid_for: [IdMap.getId("test-product")],
})
expect(AddOnModelMock.create).toBeCalledTimes(1)
expect(AddOnModelMock.create).toBeCalledWith({
name: "Chili",
prices: [
{
currency_code: "DKK",
amount: 20,
},
],
valid_for: [IdMap.getId("test-product")],
})
})
})
describe("retrieve", () => {
let result
beforeAll(async () => {
jest.clearAllMocks()
const addOnService = new AddOnService({
addOnModel: AddOnModelMock,
})
result = await addOnService.retrieve(IdMap.getId("test-add-on"))
})
it("calls model layer retrieve", async () => {
expect(AddOnModelMock.findOne).toBeCalledTimes(1)
expect(AddOnModelMock.findOne).toBeCalledWith({
_id: IdMap.getId("test-add-on"),
})
})
it("returns the add-on", () => {
expect(result).toEqual(addOns.testAddOn)
})
})
describe("update", () => {
const addOnService = new AddOnService({
addOnModel: AddOnModelMock,
productService: ProductServiceMock,
eventBusService: EventBusServiceMock,
})
beforeEach(async () => {
jest.clearAllMocks()
})
it("calls model layer create", async () => {
await addOnService.update(IdMap.getId("test-add-on"), {
name: "Chili Spice",
valid_for: [IdMap.getId("test-product"), IdMap.getId("test-product-2")],
})
expect(AddOnModelMock.updateOne).toBeCalledTimes(1)
expect(AddOnModelMock.updateOne).toBeCalledWith(
{ _id: IdMap.getId("test-add-on") },
{
$set: {
name: "Chili Spice",
valid_for: [
IdMap.getId("test-product"),
IdMap.getId("test-product-2"),
],
},
},
{ runValidators: true }
)
})
})
describe("retrieveByProduct", () => {
describe("successful retrieval", () => {
let result
beforeAll(async () => {
jest.clearAllMocks()
const addOnService = new AddOnService({
addOnModel: AddOnModelMock,
productService: ProductServiceMock,
})
result = await addOnService.retrieveByProduct(
IdMap.getId("test-product")
)
})
it("calls ProductService retrieve", async () => {
expect(ProductServiceMock.retrieve).toBeCalledTimes(1)
expect(ProductServiceMock.retrieve).toBeCalledWith(
IdMap.getId("test-product")
)
})
it("calls model layer", () => {
expect(AddOnModelMock.find).toBeCalledTimes(1)
expect(AddOnModelMock.find).toBeCalledWith({
valid_for: IdMap.getId("test-product"),
})
})
it("returns the add-ons", () => {
expect(result).toEqual([addOns.testAddOn, addOns.testAddOn2])
})
})
})
})
@@ -1,120 +0,0 @@
import _ from "lodash"
import { BaseService } from "medusa-interfaces"
import { Validator, MedusaError } from "medusa-core-utils"
class AddOnLineItemService extends BaseService {
static Events = {
UPDATED: "add_on.updated",
CREATED: "add_on.created",
}
constructor(
{
addOnService,
productService,
productVariantService,
regionService,
eventBusService,
},
options
) {
super()
this.addOnService_ = addOnService
this.productService_ = productService
this.productVariantService_ = productVariantService
this.regionService_ = regionService
this.eventBus_ = eventBusService
this.options_ = options
}
/**
* Generates a line item.
* @param {string} variantId - id of the line item variant
* @param {*} regionId - id of the cart region
* @param {*} quantity - number of items
* @param {[string]} addOnIds - id of add-ons
*/
async generate(variantId, regionId, quantity, addOnIds, metadata = {}) {
const variant = await this.productVariantService_.retrieve(variantId)
const region = await this.regionService_.retrieve(regionId)
const products = await this.productService_.list({ variants: variantId })
// this should never fail, since a variant must have a product associated
// with it to exists, but better safe than sorry
if (!products.length) {
throw new MedusaError(
MedusaError.Types.INVALID_DATA,
`Could not find product for variant with id: ${variantId}`
)
}
const product = products[0]
let unitPrice = await this.productVariantService_.getRegionPrice(
variant._id,
{regionId: region._id}
)
const addOnPrices = await Promise.all(
addOnIds.map(async (id) => {
const addOn = await this.addOnService_.retrieve(id)
// Check if any of the add-ons can't be added to the product
if (!addOn.valid_for.includes(`${product._id}`)) {
throw new MedusaError(
MedusaError.Types.INVALID_DATA,
`${addOn.name} can not be added to ${product.title}`
)
} else {
return await this.addOnService_.getRegionPrice(id, region._id)
}
})
)
unitPrice += _.sum(addOnPrices)
const line = {
title: product.title,
quantity,
thumbnail: product.thumbnail,
should_merge: false,
content: {
unit_price: unitPrice * quantity,
variant,
product,
quantity: 1,
},
should_merge: false,
metadata: {
...metadata,
add_ons: addOnIds,
},
}
return line
}
async decorate(lineItem, fields, expandFields = []) {
const requiredFields = ["_id", "metadata"]
const decorated = _.pick(lineItem, fields.concat(requiredFields))
if (
expandFields.includes("add_ons") &&
decorated.metadata &&
decorated.metadata.add_ons
) {
decorated.metadata.add_ons = await Promise.all(
decorated.metadata.add_ons.map(
async (ao) => await this.addOnService_.retrieve(ao)
)
)
}
return decorated
}
}
export default AddOnLineItemService
@@ -1,244 +0,0 @@
import _ from "lodash"
import { BaseService } from "medusa-interfaces"
import { Validator, MedusaError } from "medusa-core-utils"
class AddOnService extends BaseService {
static Events = {
UPDATED: "add_on.updated",
CREATED: "add_on.created",
}
constructor(
{
addOnModel,
productService,
productVariantService,
regionService,
eventBusService,
},
options
) {
super()
this.addOnModel_ = addOnModel
this.productService_ = productService
this.productVariantService_ = productVariantService
this.regionService_ = regionService
this.eventBus_ = eventBusService
this.options_ = options
}
/**
* Used to validate add-on ids. Throws an error if the cast fails
* @param {string} rawId - the raw add-on id to validate.
* @return {string} the validated id
*/
validateId_(rawId) {
return rawId
}
/**
* @param {Object} selector - the query object for find
* @return {Promise} the result of the find operation
*/
list(selector, offset, limit) {
return this.addOnModel_.find(selector, {}, offset, limit)
}
/**
* Gets an add-on by id.
* @param {string} addOnId - the id of the add-on to get.
* @return {Promise<AddOn>} the add-on document.
*/
async retrieve(addOnId) {
const validatedId = this.validateId_(addOnId)
const addOn = await this.addOnModel_
.findOne({ _id: validatedId })
.catch((err) => {
throw new MedusaError(MedusaError.Types.DB_ERROR, err.message)
})
if (!addOn) {
throw new MedusaError(
MedusaError.Types.NOT_FOUND,
`Add-on with ${addOnId} was not found`
)
}
return addOn
}
/**
* Creates an add-on.
* @param {object} addOn - the add-on to create
* @return {Promise} resolves to the creation result.
*/
async create(addOn) {
await Promise.all(
addOn.valid_for.map((prodId) => {
this.productService_.retrieve(prodId)
})
)
return this.addOnModel_
.create(addOn)
.then((result) => {
this.eventBus_.emit(AddOnService.Events.CREATED, result)
return result
})
.catch((err) => {
throw new MedusaError(MedusaError.Types.DB_ERROR, err.message)
})
}
/**
* Deletes an add-on.
* @param {object} addOnId - the add-on to delete
* @return {Promise} resolves to the deletion result.
*/
async delete(addOnId) {
const addOn = await this.retrieve(addOnId)
return this.addOnModel_.deleteOne({ _id: addOn._id })
}
/**
* Retrieves all valid add-ons for a given product.
* @param {object} productId - the product id to find add-ons for
* @return {Promise} returns a promise containing all add-ons for the product
*/
async retrieveByProduct(productId) {
const product = await this.productService_.retrieve(productId)
return this.addOnModel_.find({ valid_for: product._id })
}
/**
* Updates an add-on. Metadata updates should use dedicated methods, e.g.
* `setMetadata`, etc. The function will throw errors if metadata updates
* are attempted.
* @param {string} addOnId - the id of the add-on. Must be a string that
* can be casted to an ObjectId
* @param {object} update - an object with the update values.
* @return {Promise} resolves to the update result.
*/
async update(addOnId, update) {
const validatedId = this.validateId_(addOnId)
await Promise.all(
update.valid_for.map((prodId) => {
this.productService_.retrieve(prodId)
})
)
if (update.metadata) {
throw new MedusaError(
MedusaError.Types.INVALID_DATA,
"Use setMetadata to update metadata fields"
)
}
return this.addOnModel_
.updateOne(
{ _id: validatedId },
{ $set: update },
{ runValidators: true }
)
.catch((err) => {
throw new MedusaError(MedusaError.Types.DB_ERROR, err.message)
})
}
/**
* Gets the price specific to a region. If no region specific money amount
* exists the function will try to use a currency price. If no default
* currency price exists the function will throw an error.
* @param {string} addOnId - the id of the add-on to get price from
* @param {string} regionId - the id of the region to get price for
* @return {number} the price specific to the region
*/
async getRegionPrice(addOnId, regionId) {
const addOn = await this.retrieve(addOnId)
const region = await this.regionService_.retrieve(regionId)
let price
addOn.prices.forEach(({ amount, currency_code }) => {
if (!price && currency_code === region.currency_code) {
// If we haven't yet found a price and the current money amount is
// the default money amount for the currency of the region we have found
// a possible price match
price = amount
} else if (region_id === region._id) {
// If the region matches directly with the money amount this is the best
// price
price = amount
}
})
// Return the price if we found a suitable match
if (price !== undefined) {
return price
}
// If we got this far no price could be found for the region
throw new MedusaError(
MedusaError.Types.NOT_FOUND,
`A price for region: ${region.name} could not be found`
)
}
/**
* Decorates a add-on with add-on variants.
* @param {AddOn} addOn - the add-on to decorate.
* @param {string[]} fields - the fields to include.
* @param {string[]} expandFields - fields to expand.
* @return {AddOn} return the decorated add-on.
*/
async decorate(addOn, fields, expandFields = []) {
const requiredFields = ["_id", "metadata"]
const decorated = _.pick(addOn, fields.concat(requiredFields))
if (expandFields.includes("valid_for")) {
decorated.valid_for = await Promise.all(
decorated.valid_for.map(
async (p) => await this.productService_.retrieve(p)
)
)
}
return decorated
}
/**
* Dedicated method to set metadata for an add-on.
* To ensure that plugins does not overwrite each
* others metadata fields, setMetadata is provided.
* @param {string} addOnId - the add-on to decorate.
* @param {string} key - key for metadata field
* @param {string} value - value for metadata field.
* @return {Promise} resolves to the updated result.
*/
async setMetadata(addOnId, key, value) {
const validatedId = this.validateId_(addOnId)
if (typeof key !== "string") {
throw new MedusaError(
MedusaError.Types.INVALID_ARGUMENT,
"Key type is invalid. Metadata keys must be strings"
)
}
const keyPath = `metadata.${key}`
return this.addOnModel_
.updateOne({ _id: validatedId }, { $set: { [keyPath]: value } })
.then((result) => {
this.eventBus_.emit(AddOnService.Events.UPDATED, result)
return result
})
.catch((err) => {
throw new MedusaError(MedusaError.Types.DB_ERROR, err.message)
})
}
}
export default AddOnService
File diff suppressed because it is too large Load Diff
@@ -32,8 +32,7 @@
"medusa-interfaces": "1.x"
},
"dependencies": {
"axios": "^0.20.0",
"mongoose": "^5.8.0"
"axios": "^0.20.0"
},
"gitHead": "41a5425405aea5045a26def95c0dc00cf4a5a44d"
}
@@ -1,13 +0,0 @@
{
"plugins": [
"@babel/plugin-proposal-class-properties",
"@babel/plugin-transform-classes",
"@babel/plugin-transform-instanceof"
],
"presets": ["@babel/preset-env"],
"env": {
"test": {
"plugins": ["@babel/plugin-transform-runtime"]
}
}
}
@@ -1,14 +0,0 @@
dist/
node_modules/
.DS_store
.env*
/*.js
!index.js
yarn.lock
yarn-error.log
/api
/services
/models
/subscribers
@@ -1,225 +0,0 @@
# Change Log
All notable changes to this project will be documented in this file.
See [Conventional Commits](https://conventionalcommits.org) for commit guidelines.
## [1.1.37](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.1.36...medusa-plugin-permissions@1.1.37) (2022-01-11)
**Note:** Version bump only for package medusa-plugin-permissions
## [1.1.36](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.1.35...medusa-plugin-permissions@1.1.36) (2021-12-29)
**Note:** Version bump only for package medusa-plugin-permissions
## [1.1.35](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.1.34...medusa-plugin-permissions@1.1.35) (2021-12-17)
**Note:** Version bump only for package medusa-plugin-permissions
## [1.1.34](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.1.33...medusa-plugin-permissions@1.1.34) (2021-12-08)
**Note:** Version bump only for package medusa-plugin-permissions
## [1.1.33](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.1.32...medusa-plugin-permissions@1.1.33) (2021-11-23)
**Note:** Version bump only for package medusa-plugin-permissions
## [1.1.32](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.1.31...medusa-plugin-permissions@1.1.32) (2021-11-22)
**Note:** Version bump only for package medusa-plugin-permissions
## [1.1.31](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.1.30...medusa-plugin-permissions@1.1.31) (2021-11-19)
**Note:** Version bump only for package medusa-plugin-permissions
## [1.1.30](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.1.29...medusa-plugin-permissions@1.1.30) (2021-11-19)
### Features
- Typescript for API layer ([#817](https://github.com/medusajs/medusa/issues/817)) ([373532e](https://github.com/medusajs/medusa/commit/373532ecbc8196f47e71af95a8cf82a14a4b1f9e))
## [1.1.29](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.1.28...medusa-plugin-permissions@1.1.29) (2021-10-18)
**Note:** Version bump only for package medusa-plugin-permissions
## [1.1.28](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.1.27...medusa-plugin-permissions@1.1.28) (2021-10-18)
**Note:** Version bump only for package medusa-plugin-permissions
## [1.1.27](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.1.25...medusa-plugin-permissions@1.1.27) (2021-10-18)
**Note:** Version bump only for package medusa-plugin-permissions
## [1.1.26](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.1.25...medusa-plugin-permissions@1.1.26) (2021-10-18)
**Note:** Version bump only for package medusa-plugin-permissions
## [1.1.25](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.1.24...medusa-plugin-permissions@1.1.25) (2021-09-15)
**Note:** Version bump only for package medusa-plugin-permissions
## [1.1.24](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.1.23...medusa-plugin-permissions@1.1.24) (2021-09-14)
**Note:** Version bump only for package medusa-plugin-permissions
## [1.1.23](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.1.22...medusa-plugin-permissions@1.1.23) (2021-08-05)
**Note:** Version bump only for package medusa-plugin-permissions
## [1.1.22](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.1.21...medusa-plugin-permissions@1.1.22) (2021-07-26)
**Note:** Version bump only for package medusa-plugin-permissions
## [1.1.21](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.1.19...medusa-plugin-permissions@1.1.21) (2021-07-15)
**Note:** Version bump only for package medusa-plugin-permissions
## [1.1.20](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.1.19...medusa-plugin-permissions@1.1.20) (2021-07-15)
**Note:** Version bump only for package medusa-plugin-permissions
## [1.1.19](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.1.18...medusa-plugin-permissions@1.1.19) (2021-07-02)
**Note:** Version bump only for package medusa-plugin-permissions
## [1.1.18](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.1.17...medusa-plugin-permissions@1.1.18) (2021-06-22)
### Bug Fixes
- release assist ([668e8a7](https://github.com/medusajs/medusa/commit/668e8a740200847fc2a41c91d2979097f1392532))
## [1.1.17](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.1.16...medusa-plugin-permissions@1.1.17) (2021-06-09)
**Note:** Version bump only for package medusa-plugin-permissions
## [1.1.16](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.1.15...medusa-plugin-permissions@1.1.16) (2021-06-09)
**Note:** Version bump only for package medusa-plugin-permissions
## [1.1.15](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.1.14...medusa-plugin-permissions@1.1.15) (2021-06-09)
**Note:** Version bump only for package medusa-plugin-permissions
## [1.1.14](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.1.13...medusa-plugin-permissions@1.1.14) (2021-06-09)
**Note:** Version bump only for package medusa-plugin-permissions
## [1.1.13](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.1.12...medusa-plugin-permissions@1.1.13) (2021-06-08)
**Note:** Version bump only for package medusa-plugin-permissions
## [1.1.12](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.1.9...medusa-plugin-permissions@1.1.12) (2021-04-28)
**Note:** Version bump only for package medusa-plugin-permissions
## [1.1.11](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.1.10...medusa-plugin-permissions@1.1.11) (2021-04-20)
**Note:** Version bump only for package medusa-plugin-permissions
## [1.1.10](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.1.9...medusa-plugin-permissions@1.1.10) (2021-04-20)
**Note:** Version bump only for package medusa-plugin-permissions
## [1.1.9](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.1.8...medusa-plugin-permissions@1.1.9) (2021-04-13)
### Bug Fixes
- merge develop ([2982a8e](https://github.com/medusajs/medusa/commit/2982a8e682e90beb4549d969d9d3b04d78a46a2d))
- merge develop ([a468c45](https://github.com/medusajs/medusa/commit/a468c451e82c68f41b5005a2e480057f6124aaa6))
## [1.1.8](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.1.7...medusa-plugin-permissions@1.1.8) (2021-04-13)
**Note:** Version bump only for package medusa-plugin-permissions
## [1.1.7](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.1.6...medusa-plugin-permissions@1.1.7) (2021-03-30)
**Note:** Version bump only for package medusa-plugin-permissions
## [1.1.6](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.1.5...medusa-plugin-permissions@1.1.6) (2021-03-17)
**Note:** Version bump only for package medusa-plugin-permissions
## [1.1.5](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.1.3...medusa-plugin-permissions@1.1.5) (2021-03-17)
**Note:** Version bump only for package medusa-plugin-permissions
## [1.1.4](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.1.3...medusa-plugin-permissions@1.1.4) (2021-03-17)
**Note:** Version bump only for package medusa-plugin-permissions
## [1.1.3](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.1.2...medusa-plugin-permissions@1.1.3) (2021-02-17)
**Note:** Version bump only for package medusa-plugin-permissions
## [1.1.2](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.1.1...medusa-plugin-permissions@1.1.2) (2021-02-03)
**Note:** Version bump only for package medusa-plugin-permissions
## [1.1.1](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.1.0...medusa-plugin-permissions@1.1.1) (2021-01-27)
**Note:** Version bump only for package medusa-plugin-permissions
# [1.1.0](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.0.13...medusa-plugin-permissions@1.1.0) (2021-01-26)
**Note:** Version bump only for package medusa-plugin-permissions
## [1.0.13](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.0.12...medusa-plugin-permissions@1.0.13) (2020-12-17)
**Note:** Version bump only for package medusa-plugin-permissions
## [1.0.12](https://github.com/medusajs/medusa/compare/medusa-plugin-permissions@1.0.11...medusa-plugin-permissions@1.0.12) (2020-11-24)
**Note:** Version bump only for package medusa-plugin-permissions
## 1.0.11 (2020-10-19)
## 1.0.10 (2020-09-09)
### Bug Fixes
- updates license ([db519fb](https://github.com/medusajs/medusa/commit/db519fbaa6f8ad02c19cbecba5d4f28ba1ee81aa))
## 1.0.7 (2020-09-07)
## 1.0.1 (2020-09-05)
## 1.0.1-beta.0 (2020-09-04)
# 1.0.0 (2020-09-03)
# 1.0.0-alpha.30 (2020-08-28)
# 1.0.0-alpha.27 (2020-08-27)
# 1.0.0-alpha.26 (2020-08-27)
# 1.0.0-alpha.24 (2020-08-27)
# 1.0.0-alpha.3 (2020-08-20)
# 1.0.0-alpha.2 (2020-08-20)
# 1.0.0-alpha.1 (2020-08-20)
# 1.0.0-alpha.0 (2020-08-20)
### Reverts
- Revert "[medusa-interfaces] : Adds decorator functionality to BaseService (#39)" (#41) ([2273cc5](https://github.com/medusajs/medusa/commit/2273cc519ad4d6ae16157173aba3955d16745e1d)), closes [#39](https://github.com/medusajs/medusa/issues/39) [#41](https://github.com/medusajs/medusa/issues/41)
## [1.0.10](https://github.com/medusajs/medusa/compare/v1.0.9...v1.0.10) (2020-09-09)
### Bug Fixes
- updates license ([db519fb](https://github.com/medusajs/medusa/commit/db519fbaa6f8ad02c19cbecba5d4f28ba1ee81aa))
@@ -1,40 +0,0 @@
{
"name": "medusa-plugin-permissions",
"version": "1.1.37",
"description": "Role permission for Medusa core",
"main": "dist/index.js",
"repository": {
"type": "git",
"url": "https://github.com/medusajs/medusa",
"directory": "packages/medusa-plugin-permissions"
},
"scripts": {
"build": "babel src --out-dir . --ignore **/__tests__",
"prepare": "cross-env NODE_ENV=production npm run build",
"watch": "babel -w src --out-dir . --ignore **/__tests__",
"test": "jest"
},
"author": "Oliver Juhl",
"license": "MIT",
"devDependencies": {
"@babel/cli": "^7.7.5",
"@babel/core": "^7.7.5",
"@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/runtime": "^7.7.6",
"cross-env": "^5.2.1",
"jest": "^25.5.2"
},
"peerDependencies": {
"medusa-interfaces": "1.x"
},
"dependencies": {
"medusa-core-utils": "^1.1.31",
"medusa-test-utils": "^1.1.37",
"mongoose": "^5.8.0"
},
"gitHead": "c46300d58fbfd0b2dc2c02745ae143e6247e885b"
}
@@ -1,16 +0,0 @@
// This middleware is injected to ensure authorization of requests
// Since this middleware uses the user object on the request, this should be
// injected after authentication in the core middleware, hence we name
// the middleware postAuth.
export default {
postAuthentication: () => {
return (err, req, res, next) => {
const permissionService = req.scope.resolve("permissionService")
if (permissionService.hasPermission(req.user, req.method, req.path)) {
next()
} else {
res.status(422)
}
}
}
}
@@ -1,36 +0,0 @@
import { IdMap } from "medusa-test-utils"
export const permissions = {
productEditorPermission: {
_id: IdMap.getId("product_editor"),
name: "product_editor",
permissions: [
{
method: "POST",
endpoint: "/products",
},
{
method: "GET",
endpoint: "/products",
},
{
method: "PUT",
endpoint: "/products",
},
],
},
}
export const RoleModelMock = {
create: jest.fn().mockReturnValue(Promise.resolve()),
deleteOne: jest.fn().mockReturnValue(Promise.resolve()),
findOne: jest.fn().mockImplementation(query => {
if (query.name === "product_editor") {
return Promise.resolve(permissions.productEditorPermission)
}
return Promise.resolve(undefined)
}),
updateOne: jest.fn().mockImplementation((query, update) => {
return Promise.resolve()
}),
}
@@ -1,13 +0,0 @@
import { BaseModel } from "medusa-interfaces"
import PermissionSchema from "./schemas/permission"
class RoleModel extends BaseModel {
static modelName = "Role"
static schema = {
name: { type: String, required: true, unique: true },
permissions: { type: [PermissionSchema], required: true, default: [] },
}
}
export default RoleModel
@@ -1,6 +0,0 @@
import mongoose from "mongoose"
export default new mongoose.Schema({
method: { type: String },
endpoint: { type: String },
})
@@ -1,162 +0,0 @@
import { BaseService } from "medusa-interfaces"
import { Validator, MedusaError } from "medusa-core-utils"
class PermissionService extends BaseService {
constructor({ userService, roleModel }) {
super()
/** @private @const {UserService} */
this.userService_ = userService
/** @private @const {RoleModel} */
this.roleModel_ = roleModel
}
validatePermission_(permission) {
const schema = Validator.object({
method: Validator.string().valid(
"POST",
"GET",
"PUT",
"PATCH",
"DELETE",
"CONNECT",
"OPTIONS",
"HEAD",
"TRACE"
),
endpoint: Validator.string(),
})
const { value, error } = schema.validate(permission)
if (error) {
throw new MedusaError(
MedusaError.Types.INVALID_ARGUMENT,
"Permission is not valid"
)
}
return value
}
async retrieveRole(name) {
const role = await this.roleModel_.findOne({ name }).catch((err) => {
throw new MedusaError(MedusaError.Types.DB_ERROR, err.message)
})
if (!role) {
throw new MedusaError(
MedusaError.Types.NOT_FOUND,
`${name} does not exist. Use method createRole to create it.`
)
}
return role
}
async hasPermission(user, method, endpoint) {
if (!user) return false
for (let i = 0; i < user.metadata.roles.length; i++) {
const role = user.metadata.roles[i]
const permissions = await this.retrieveRole(role)
return permissions.permissions.some((action) => {
return action.method === method && action.endpoint === endpoint
})
}
return false
}
async createRole(roleName, permissions) {
const validatedPermissions = permissions.map((permission) =>
this.validatePermission_(permission)
)
return this.retrieveRole(roleName)
.then((role) => {
throw new MedusaError(
MedusaError.Types.INVALID_ARGUMENT,
`${role.name} already exists`
)
})
.catch((error) => {
if (error.name === MedusaError.Types.NOT_FOUND) {
return this.roleModel_.create({
name: roleName,
permissions: validatedPermissions,
})
} else {
throw error
}
})
}
async deleteRole(roleName) {
const role = await this.retrieve(roleName)
// Delete is idempotent, but we return a promise to allow then-chaining
if (!role) {
return Promise.resolve()
}
return this.roleModel_
.deleteOne({
_id: role._id,
})
.catch((err) => {
throw new MedusaError(MedusaError.Types.DB_ERROR, err.message)
})
}
async addPermission(roleName, permission) {
const role = await this.retrieveRole(roleName)
const validatedPermission = this.validatePermission_(permission)
return this.roleModel_.updateOne(
{ _id: role._id },
{ $push: { permissions: validatedPermission } }
)
}
async removePermission(roleName, permission) {
const role = await this.retrieveRole(roleName)
const validatedPermission = this.validatePermission_(permission)
return this.roleModel_.updateOne(
{ _id: role._id },
{ $pull: { permissions: validatedPermission } }
)
}
async grantRole(userId, roleName) {
const role = await this.retrieveRole(roleName)
const user = await this.userService_.retrieve(userId)
if (!user.metadata.roles) {
return this.userService_.setMetadata(userId, "roles", [roleName])
}
if (user.metadata.roles.includes(role.name)) {
throw new MedusaError(
MedusaError.Types.DB_ERROR,
`User already has role: ${role.name}`
)
}
user.metadata.roles.push(roleName)
return this.userService_.setMetadata(userId, "roles", user.metadata.roles)
}
async revokeRole(userId, roleName) {
const user = await this.userService_.retrieve(userId)
if (!user.metadata.roles || !user.metadata.roles.includes(roleName)) {
// revokeRole is idempotent, we return a promise to allow then-chaining
return Promise.resolve()
}
// remove role from metadata.roles
const newRoles = user.metadata.roles.filter((r) => r !== roleName)
return this.userService_.setMetadata(userId, "roles", newRoles)
}
}
export default PermissionService
File diff suppressed because it is too large Load Diff
@@ -1,5 +1,3 @@
import mongoose from "mongoose"
import { IdMap } from "medusa-test-utils"
import MiddlewareService from "../middleware"
describe("MiddlewareService", () => {
@@ -1,11 +1,11 @@
import { BaseService } from "medusa-interfaces"
import { MedusaError } from "medusa-core-utils"
import { BaseService } from "medusa-interfaces"
import { v4 } from "uuid"
const KEY_LOCKED_TIMEOUT = 1000
class IdempotencyKeyService extends BaseService {
constructor({ manager, idempotencyKeyRepository, transactionService }) {
constructor({ manager, idempotencyKeyRepository }) {
super()
/** @private @constant {EntityManager} */
@@ -13,9 +13,6 @@ class IdempotencyKeyService extends BaseService {
/** @private @constant {IdempotencyKeyRepository} */
this.idempotencyKeyRepository_ = idempotencyKeyRepository
/** @private @constant {TransactionService} */
this.transactionService_ = transactionService
}
/**
@@ -88,7 +85,6 @@ class IdempotencyKeyService extends BaseService {
/**
* Locks an idempotency.
* @param {string} idempotencyKey - key to lock
* @param {object} session - mongoose transaction session
* @return {Promise} result of the update operation
*/
async lock(idempotencyKey) {
+12 -13
View File
@@ -1,15 +1,16 @@
export { default as AuthService } from "./auth"
export { default as BatchJobService } from "./batch-job"
export { default as CartService } from "./cart"
export { default as ClaimService } from "./claim"
export { default as ClaimItemService } from "./claim-item"
export { default as ClaimService } from "./claim"
export { default as CustomShippingOptionService } from "./custom-shipping-option"
export { default as CustomerService } from "./customer"
export { default as CustomerGroupService } from "./customer-group"
export { default as CustomerService } from "./customer"
export { default as DiscountService } from "./discount"
export { default as DraftOrderService } from "./draft-order"
export { default as EventBusService } from "./event-bus"
export { default as FulfillmentService } from "./fulfillment"
export { default as FulfillmentProviderService } from "./fulfillment-provider"
export { default as FulfillmentService } from "./fulfillment"
export { default as GiftCardService } from "./gift-card"
export { default as IdempotencyKeyService } from "./idempotency-key"
export { default as InventoryService } from "./inventory"
@@ -20,25 +21,23 @@ export { default as NotificationService } from "./notification"
export { default as OauthService } from "./oauth"
export { default as OrderService } from "./order"
export { default as PaymentProviderService } from "./payment-provider"
export { default as ProductService } from "./product"
export { default as PricingService } from "./pricing"
export { default as ProductCollectionService } from "./product-collection"
export { default as ProductService } from "./product"
export { default as ProductTypeService } from "./product-type"
export { default as ProductVariantService } from "./product-variant"
export { default as QueryBuilderService } from "./query-builder"
export { default as RegionService } from "./region"
export { default as ReturnService } from "./return"
export { default as ReturnReasonService } from "./return-reason"
export { default as ReturnService } from "./return"
export { default as SearchService } from "./search"
export { default as ShippingOptionService } from "./shipping-option"
export { default as ShippingProfileService } from "./shipping-profile"
export { default as StoreService } from "./store"
export { default as StrategyResolverService } from "./strategy-resolver"
export { default as SwapService } from "./swap"
export { default as SystemPaymentProviderService } from "./system-payment-provider"
export { default as TotalsService } from "./totals"
export { default as TransactionService } from "./transaction"
export { default as UserService } from "./user"
export { default as TaxRateService } from "./tax-rate"
export { default as TaxProviderService } from "./tax-provider"
export { default as ProductTypeService } from "./product-type"
export { default as PricingService } from "./pricing"
export { default as BatchJobService } from "./batch-job"
export { default as StrategyResolverService } from "./strategy-resolver"
export { default as TaxRateService } from "./tax-rate"
export { default as TotalsService } from "./totals"
export { default as UserService } from "./user"
@@ -1,14 +0,0 @@
import { BaseService } from "medusa-interfaces"
import mongoose from "mongoose"
class TransactionService extends BaseService {
constructor() {
super()
}
async createSession() {
return mongoose.startSession()
}
}
export default TransactionService