chore: Remove legacy MWH modules (#7213)
* chore: Remove legacy MWH modules * chore: Add stock-location deps
This commit is contained in:
@@ -0,0 +1,6 @@
|
||||
/dist
|
||||
node_modules
|
||||
.DS_store
|
||||
.env*
|
||||
.env
|
||||
*.sql
|
||||
@@ -0,0 +1,23 @@
|
||||
# @medusajs/user
|
||||
|
||||
## 0.0.3
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- [#6758](https://github.com/medusajs/medusa/pull/6758) [`d930ebc1ed`](https://github.com/medusajs/medusa/commit/d930ebc1ed711631454376a13a22b66f31cc1a7d) Thanks [@pKorsholm](https://github.com/pKorsholm)! - feat(user): invite expiry fix
|
||||
|
||||
- Updated dependencies [[`06f22bb48a`](https://github.com/medusajs/medusa/commit/06f22bb48ad1fe73577657b8c5db055312f16a0d), [`deab12e27e`](https://github.com/medusajs/medusa/commit/deab12e27e8249e26d24d7bc904c18195679ff24), [`56481e683d`](https://github.com/medusajs/medusa/commit/56481e683d33ff98f0d4c4e144873bb23f993c9c), [`9073d7aba3`](https://github.com/medusajs/medusa/commit/9073d7aba3419e4dc0a206473291a46ebd79b8c1), [`4974f5e455`](https://github.com/medusajs/medusa/commit/4974f5e4557bd64a328a881ec02b91e15485bd23), [`05e857d256`](https://github.com/medusajs/medusa/commit/05e857d25657b5576a891c9b48c19c1759c70701), [`1ef9c78cea`](https://github.com/medusajs/medusa/commit/1ef9c78cea080c3b7c136f909c6cddec9d8f0c62)]:
|
||||
- @medusajs/modules-sdk@1.12.10
|
||||
- @medusajs/types@1.11.15
|
||||
- @medusajs/utils@1.11.8
|
||||
|
||||
## 0.0.2
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- [#6700](https://github.com/medusajs/medusa/pull/6700) [`8f8a4f9b13`](https://github.com/medusajs/medusa/commit/8f8a4f9b1353087d98f6cc75346d43a7f49901a8) Thanks [@olivermrbl](https://github.com/olivermrbl)! - chore: Version all modules to allow for initial testing
|
||||
|
||||
- Updated dependencies [[`1fd0457c15`](https://github.com/medusajs/medusa/commit/1fd0457c153b2ef7657c052878d8e5364e1b324a), [`9288f53327`](https://github.com/medusajs/medusa/commit/9288f53327b8ce617af92ed8d14d9459cbfeb13c), [`d4b921f3db`](https://github.com/medusajs/medusa/commit/d4b921f3dbe0a38f1565a8de759996c70798d58e), [`ac86362e81`](https://github.com/medusajs/medusa/commit/ac86362e81d8523cb8e3dfad026fc94658513018), [`e4acde1aa2`](https://github.com/medusajs/medusa/commit/e4acde1aa2eb57f07e6692fe8b61f728948b9a96), [`1a661adf3e`](https://github.com/medusajs/medusa/commit/1a661adf3ef4991aa6e237dd894b6a5c47cd4aca), [`56cbf88115`](https://github.com/medusajs/medusa/commit/56cbf88115994adea7037c3f2814f0c96af3cfc0), [`36a61658f9`](https://github.com/medusajs/medusa/commit/36a61658f969a7b19c84a1e621ad1464927cafb1), [`04a532e5ef`](https://github.com/medusajs/medusa/commit/04a532e5efabbf75b1e4155520b1da175b686ffc), [`c319edb8e0`](https://github.com/medusajs/medusa/commit/c319edb8e0ecd13d086652147667916e5abab2d8), [`0b9fcb6324`](https://github.com/medusajs/medusa/commit/0b9fcb6324eee9f2556c7e6317775fae93b12a47), [`586df9da25`](https://github.com/medusajs/medusa/commit/586df9da250e492442769f5bac2f8b3de1d46f05), [`b3d826497b`](https://github.com/medusajs/medusa/commit/b3d826497b3dae5e1b26b7924706c24fd5e87ca5), [`a86c87fe14`](https://github.com/medusajs/medusa/commit/a86c87fe1442afce9285e39255914e01012b4449), [`640eccd5dd`](https://github.com/medusajs/medusa/commit/640eccd5ddbb163e0f987ce6c772f1129c2e2632), [`8ea37d03c9`](https://github.com/medusajs/medusa/commit/8ea37d03c914a5004a3e42770668b2d1f7f8f564), [`339a946f38`](https://github.com/medusajs/medusa/commit/339a946f389033c21e05338f9dbf07d88e140533), [`ac829fc67f`](https://github.com/medusajs/medusa/commit/ac829fc67f7495b08f28e55923c59f0fd6320311), [`d9d5afc3cf`](https://github.com/medusajs/medusa/commit/d9d5afc3cfc29221d0e65bff7b78474a8fb8f31f), [`c3c4f49fc2`](https://github.com/medusajs/medusa/commit/c3c4f49fc2126f950e69e291ca939ca88a15afd3), [`9288f53327`](https://github.com/medusajs/medusa/commit/9288f53327b8ce617af92ed8d14d9459cbfeb13c), [`0d46abf0ff`](https://github.com/medusajs/medusa/commit/0d46abf0ffa4c5e03bf7d2a9cdf1db828a76bea8), [`fafde4f54d`](https://github.com/medusajs/medusa/commit/fafde4f54d3ef75a7d382e6cbf94e38b3deae99b), [`8dad2b51a2`](https://github.com/medusajs/medusa/commit/8dad2b51a26c4c3c14a6c95f70424c8bef2ad63e), [`0c705d7bd4`](https://github.com/medusajs/medusa/commit/0c705d7bd41a768c48017ae95b3c8414d96c6acb), [`a6d7070dd6`](https://github.com/medusajs/medusa/commit/a6d7070dd669c21ea19d70434d42c2f8167dc309), [`1d91b7429b`](https://github.com/medusajs/medusa/commit/1d91b7429beebd6f09d5027f7f7e1fe74ce3a8ff), [`168f02f138`](https://github.com/medusajs/medusa/commit/168f02f138ad101e1013f2c8c3f8dc19de12accf), [`1ed5f918c3`](https://github.com/medusajs/medusa/commit/1ed5f918c31794a70aca4a4e4cd83cf456593baa), [`c20eb15cd9`](https://github.com/medusajs/medusa/commit/c20eb15cd9b1bd90c8d01f68eca6f0f181cd902d), [`e5945479e0`](https://github.com/medusajs/medusa/commit/e5945479e091d9560ae3e7240306a31031ef4584), [`f5c2256286`](https://github.com/medusajs/medusa/commit/f5c22562867f412040f8bc6c55ab5de3a3735e62), [`000eb61e33`](https://github.com/medusajs/medusa/commit/000eb61e33e0302db95ee6ad1656ea9b430ed471), [`d550be3685`](https://github.com/medusajs/medusa/commit/d550be3685423218d47a20c57a5e06758f4a961a), [`62a7bcc30c`](https://github.com/medusajs/medusa/commit/62a7bcc30cbc7b234b2b51d7858439951a84edeb), [`8f8a4f9b13`](https://github.com/medusajs/medusa/commit/8f8a4f9b1353087d98f6cc75346d43a7f49901a8), [`6500f18b9b`](https://github.com/medusajs/medusa/commit/6500f18b9b80c5c9c473489e7e740d55dca74303), [`ce39b9b66e`](https://github.com/medusajs/medusa/commit/ce39b9b66e8c277ec0691ea6d0a950003be09cc1), [`a6a4b3f01a`](https://github.com/medusajs/medusa/commit/a6a4b3f01a6d2bd97b1580c59134279a1b033a5d), [`4d51f095b3`](https://github.com/medusajs/medusa/commit/4d51f095b3f98f468cefb760512563f7b77bb9cf), [`4625bd1241`](https://github.com/medusajs/medusa/commit/4625bd12416275b09c22cde4a09cb0f68df5d7c1), [`56b0b45304`](https://github.com/medusajs/medusa/commit/56b0b4530401a6ec5aa155874d371e45bb388fe2), [`cc1b66842c`](https://github.com/medusajs/medusa/commit/cc1b66842cbb37c6eab84e2d8b74844c214f38d7), [`24fb102a56`](https://github.com/medusajs/medusa/commit/24fb102a564b1253d1f8b039bb1e435cc5312fbb), [`e85463b2a7`](https://github.com/medusajs/medusa/commit/e85463b2a717751de2e21c39a4c745449b31affe)]:
|
||||
- @medusajs/types@1.11.14
|
||||
- @medusajs/utils@1.11.7
|
||||
- @medusajs/modules-sdk@1.12.9
|
||||
@@ -0,0 +1,3 @@
|
||||
# User Module
|
||||
|
||||
The User Module is Medusa’s user engine.
|
||||
@@ -0,0 +1,17 @@
|
||||
import { SqlEntityManager } from "@mikro-orm/postgresql"
|
||||
import { Invite } from "@models"
|
||||
import { CreateInviteDTO } from "../../../types/dist"
|
||||
|
||||
export const createInvites = async (
|
||||
manager: SqlEntityManager,
|
||||
inviteData: (CreateInviteDTO & { id?: string })[]
|
||||
) => {
|
||||
const invites: Invite[] = []
|
||||
|
||||
for (const invite of inviteData) {
|
||||
const inv = manager.create(Invite, invite)
|
||||
invites.push(inv)
|
||||
}
|
||||
|
||||
await manager.persistAndFlush(invites)
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { SqlEntityManager } from "@mikro-orm/postgresql"
|
||||
import { User } from "@models"
|
||||
import { CreateUserDTO } from "../../../types/dist"
|
||||
|
||||
export const createUsers = async (
|
||||
manager: SqlEntityManager,
|
||||
userData: (CreateUserDTO & { id?: string })[]
|
||||
) => {
|
||||
const users: User[] = []
|
||||
|
||||
for (const user of userData) {
|
||||
const usr = manager.create(User, user)
|
||||
users.push(usr)
|
||||
}
|
||||
|
||||
await manager.persistAndFlush(users)
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
import { IUserModuleService } from "@medusajs/types/dist/user"
|
||||
import { MockEventBusService } from "medusa-test-utils"
|
||||
import { Modules } from "@medusajs/modules-sdk"
|
||||
import { UserEvents } from "@medusajs/utils"
|
||||
import { createInvites } from "../../../__fixtures__/invite"
|
||||
import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils"
|
||||
|
||||
jest.setTimeout(30000)
|
||||
|
||||
const today = new Date()
|
||||
const expireDate = new Date(today.setDate(today.getDate() + 10))
|
||||
|
||||
const defaultInviteData = [
|
||||
{
|
||||
id: "1",
|
||||
email: "user_1@test.com",
|
||||
token: "test",
|
||||
expires_at: expireDate,
|
||||
},
|
||||
{
|
||||
id: "2",
|
||||
email: "user_2@test.com",
|
||||
token: "test",
|
||||
expires_at: expireDate,
|
||||
},
|
||||
]
|
||||
|
||||
moduleIntegrationTestRunner({
|
||||
moduleName: Modules.USER,
|
||||
moduleOptions: {
|
||||
jwt_secret: "test",
|
||||
},
|
||||
injectedDependencies: {
|
||||
eventBusModuleService: new MockEventBusService(),
|
||||
},
|
||||
testSuite: ({
|
||||
MikroOrmWrapper,
|
||||
service,
|
||||
}: SuiteOptions<IUserModuleService>) => {
|
||||
describe("UserModuleService - Invite", () => {
|
||||
beforeEach(async () => {
|
||||
jest.clearAllMocks()
|
||||
})
|
||||
|
||||
describe("listInvites", () => {
|
||||
it("should list invites", async () => {
|
||||
await createInvites(MikroOrmWrapper.forkManager(), defaultInviteData)
|
||||
|
||||
const invites = await service.listInvites()
|
||||
|
||||
expect(invites).toEqual([
|
||||
expect.objectContaining({
|
||||
id: "1",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
id: "2",
|
||||
}),
|
||||
])
|
||||
})
|
||||
|
||||
it("should list invites by id", async () => {
|
||||
await createInvites(MikroOrmWrapper.forkManager(), defaultInviteData)
|
||||
const invites = await service.listInvites({
|
||||
id: ["1"],
|
||||
})
|
||||
|
||||
expect(invites).toEqual([
|
||||
expect.objectContaining({
|
||||
id: "1",
|
||||
}),
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe("listAndCountInvites", () => {
|
||||
it("should list and count invites", async () => {
|
||||
await createInvites(MikroOrmWrapper.forkManager(), defaultInviteData)
|
||||
const [invites, count] = await service.listAndCountInvites()
|
||||
|
||||
expect(count).toEqual(2)
|
||||
expect(invites).toEqual([
|
||||
expect.objectContaining({
|
||||
id: "1",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
id: "2",
|
||||
}),
|
||||
])
|
||||
})
|
||||
|
||||
it("should listAndCount invites by id", async () => {
|
||||
await createInvites(MikroOrmWrapper.forkManager(), defaultInviteData)
|
||||
const [invites, count] = await service.listAndCountInvites({
|
||||
id: "1",
|
||||
})
|
||||
|
||||
expect(count).toEqual(1)
|
||||
expect(invites).toEqual([
|
||||
expect.objectContaining({
|
||||
id: "1",
|
||||
}),
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe("retrieveInvite", () => {
|
||||
const id = "1"
|
||||
|
||||
it("should return an invite for the given id", async () => {
|
||||
await createInvites(MikroOrmWrapper.forkManager(), defaultInviteData)
|
||||
const invite = await service.retrieveInvite(id)
|
||||
|
||||
expect(invite).toEqual(
|
||||
expect.objectContaining({
|
||||
id,
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it("should throw an error when an invite with the given id does not exist", async () => {
|
||||
const error = await service
|
||||
.retrieveInvite("does-not-exist")
|
||||
.catch((e) => e)
|
||||
|
||||
expect(error.message).toEqual(
|
||||
"Invite with id: does-not-exist was not found"
|
||||
)
|
||||
})
|
||||
|
||||
it("should throw an error when inviteId is not provided", async () => {
|
||||
const error = await service
|
||||
.retrieveInvite(undefined as unknown as string)
|
||||
.catch((e) => e)
|
||||
|
||||
expect(error.message).toEqual("invite - id must be defined")
|
||||
})
|
||||
|
||||
it("should return invite based on config select param", async () => {
|
||||
await createInvites(MikroOrmWrapper.forkManager(), defaultInviteData)
|
||||
const invite = await service.retrieveInvite(id, {
|
||||
select: ["id"],
|
||||
})
|
||||
|
||||
expect(invite).toEqual({
|
||||
id,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("updateInvite", () => {
|
||||
it("should throw an error when an id does not exist", async () => {
|
||||
const error = await service
|
||||
.updateInvites([
|
||||
{
|
||||
id: "does-not-exist",
|
||||
},
|
||||
])
|
||||
.catch((e) => e)
|
||||
|
||||
expect(error.message).toEqual(
|
||||
'Invite with id "does-not-exist" not found'
|
||||
)
|
||||
})
|
||||
|
||||
it("should emit invite updated events", async () => {
|
||||
await createInvites(MikroOrmWrapper.forkManager(), defaultInviteData)
|
||||
|
||||
jest.clearAllMocks()
|
||||
|
||||
const eventBusSpy = jest.spyOn(MockEventBusService.prototype, "emit")
|
||||
await service.updateInvites([
|
||||
{
|
||||
id: "1",
|
||||
accepted: true,
|
||||
},
|
||||
])
|
||||
|
||||
expect(eventBusSpy).toHaveBeenCalledTimes(1)
|
||||
expect(eventBusSpy).toHaveBeenCalledWith([
|
||||
expect.objectContaining({
|
||||
body: expect.objectContaining({
|
||||
data: { id: "1" },
|
||||
}),
|
||||
eventName: UserEvents.invite_updated,
|
||||
}),
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe("resendInvite", () => {
|
||||
it("should emit token generated event for invites", async () => {
|
||||
await createInvites(MikroOrmWrapper.forkManager(), defaultInviteData)
|
||||
const eventBusSpy = jest.spyOn(MockEventBusService.prototype, "emit")
|
||||
|
||||
await service.refreshInviteTokens(["1"])
|
||||
|
||||
expect(eventBusSpy).toHaveBeenCalledTimes(1)
|
||||
expect(eventBusSpy).toHaveBeenCalledWith([
|
||||
expect.objectContaining({
|
||||
body: expect.objectContaining({
|
||||
data: { id: "1" },
|
||||
}),
|
||||
eventName: UserEvents.invite_token_generated,
|
||||
}),
|
||||
])
|
||||
})
|
||||
})
|
||||
describe("createInvitie", () => {
|
||||
it("should create an invite successfully", async () => {
|
||||
await service.createInvites(defaultInviteData)
|
||||
|
||||
const [invites, count] = await service.listAndCountInvites({
|
||||
id: ["1"],
|
||||
})
|
||||
|
||||
expect(count).toEqual(1)
|
||||
expect(invites[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
id: "1",
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it("should emit invite created events", async () => {
|
||||
const eventBusSpy = jest.spyOn(MockEventBusService.prototype, "emit")
|
||||
await service.createInvites(defaultInviteData)
|
||||
|
||||
expect(eventBusSpy).toHaveBeenCalledTimes(1)
|
||||
expect(eventBusSpy).toHaveBeenCalledWith([
|
||||
expect.objectContaining({
|
||||
body: expect.objectContaining({
|
||||
data: { id: "1" },
|
||||
}),
|
||||
eventName: UserEvents.invite_created,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
body: expect.objectContaining({
|
||||
data: { id: "2" },
|
||||
}),
|
||||
eventName: UserEvents.invite_created,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
body: expect.objectContaining({
|
||||
data: { id: "1" },
|
||||
}),
|
||||
eventName: UserEvents.invite_token_generated,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
body: expect.objectContaining({
|
||||
data: { id: "2" },
|
||||
}),
|
||||
eventName: UserEvents.invite_token_generated,
|
||||
}),
|
||||
])
|
||||
})
|
||||
})
|
||||
})
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,241 @@
|
||||
import { IUserModuleService } from "@medusajs/types/dist/user"
|
||||
import { MockEventBusService } from "medusa-test-utils"
|
||||
import { Modules } from "@medusajs/modules-sdk"
|
||||
import { UserEvents } from "@medusajs/utils"
|
||||
import { createUsers } from "../../../__fixtures__/user"
|
||||
import { moduleIntegrationTestRunner, SuiteOptions } from "medusa-test-utils"
|
||||
|
||||
jest.setTimeout(30000)
|
||||
|
||||
const defaultUserData = [
|
||||
{
|
||||
id: "1",
|
||||
email: "user_1@test.com",
|
||||
},
|
||||
{
|
||||
id: "2",
|
||||
email: "user_2@test.com",
|
||||
},
|
||||
]
|
||||
|
||||
moduleIntegrationTestRunner({
|
||||
moduleName: Modules.USER,
|
||||
moduleOptions: {
|
||||
jwt_secret: "test",
|
||||
},
|
||||
injectedDependencies: {
|
||||
eventBusModuleService: new MockEventBusService(),
|
||||
},
|
||||
testSuite: ({
|
||||
MikroOrmWrapper,
|
||||
service,
|
||||
medusaApp,
|
||||
}: SuiteOptions<IUserModuleService>) => {
|
||||
describe("UserModuleService - User", () => {
|
||||
afterEach(async () => {
|
||||
jest.clearAllMocks()
|
||||
})
|
||||
|
||||
describe("list", () => {
|
||||
it("should list users", async () => {
|
||||
await createUsers(MikroOrmWrapper.forkManager(), defaultUserData)
|
||||
|
||||
const users = await service.list()
|
||||
|
||||
expect(users).toEqual([
|
||||
expect.objectContaining({
|
||||
id: "1",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
id: "2",
|
||||
}),
|
||||
])
|
||||
})
|
||||
|
||||
it("should list users by id", async () => {
|
||||
await createUsers(MikroOrmWrapper.forkManager(), defaultUserData)
|
||||
const users = await service.list({
|
||||
id: ["1"],
|
||||
})
|
||||
|
||||
expect(users).toEqual([
|
||||
expect.objectContaining({
|
||||
id: "1",
|
||||
}),
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe("listAndCount", () => {
|
||||
it("should list and count users", async () => {
|
||||
await createUsers(MikroOrmWrapper.forkManager(), defaultUserData)
|
||||
const [users, count] = await service.listAndCount()
|
||||
|
||||
expect(count).toEqual(2)
|
||||
expect(users).toEqual([
|
||||
expect.objectContaining({
|
||||
id: "1",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
id: "2",
|
||||
}),
|
||||
])
|
||||
})
|
||||
|
||||
it("should list and count users by id", async () => {
|
||||
await createUsers(MikroOrmWrapper.forkManager(), defaultUserData)
|
||||
const [Users, count] = await service.listAndCount({
|
||||
id: "1",
|
||||
})
|
||||
|
||||
expect(count).toEqual(1)
|
||||
expect(Users).toEqual([
|
||||
expect.objectContaining({
|
||||
id: "1",
|
||||
}),
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe("retrieve", () => {
|
||||
const id = "1"
|
||||
|
||||
it("should return an user for the given id", async () => {
|
||||
await createUsers(MikroOrmWrapper.forkManager(), defaultUserData)
|
||||
|
||||
const user = await service.retrieve(id)
|
||||
|
||||
expect(user).toEqual(
|
||||
expect.objectContaining({
|
||||
id,
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it("should throw an error when an user with the given id does not exist", async () => {
|
||||
const error = await service.retrieve("does-not-exist").catch((e) => e)
|
||||
|
||||
expect(error.message).toEqual(
|
||||
"User with id: does-not-exist was not found"
|
||||
)
|
||||
})
|
||||
|
||||
it("should throw an error when a userId is not provided", async () => {
|
||||
const error = await service
|
||||
.retrieve(undefined as unknown as string)
|
||||
.catch((e) => e)
|
||||
|
||||
expect(error.message).toEqual("user - id must be defined")
|
||||
})
|
||||
|
||||
it("should return user based on config select param", async () => {
|
||||
await createUsers(MikroOrmWrapper.forkManager(), defaultUserData)
|
||||
|
||||
const User = await service.retrieve(id, {
|
||||
select: ["id"],
|
||||
})
|
||||
|
||||
const serialized = JSON.parse(JSON.stringify(User))
|
||||
|
||||
expect(serialized).toEqual({
|
||||
id,
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("delete", () => {
|
||||
const id = "1"
|
||||
|
||||
it("should delete the users given an id successfully", async () => {
|
||||
await createUsers(MikroOrmWrapper.forkManager(), defaultUserData)
|
||||
|
||||
await service.delete([id])
|
||||
|
||||
const users = await service.list({
|
||||
id: [id],
|
||||
})
|
||||
|
||||
expect(users).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
|
||||
describe("update", () => {
|
||||
it("should throw an error when a id does not exist", async () => {
|
||||
const error = await service
|
||||
.update([
|
||||
{
|
||||
id: "does-not-exist",
|
||||
},
|
||||
])
|
||||
.catch((e) => e)
|
||||
|
||||
expect(error.message).toEqual(
|
||||
'User with id "does-not-exist" not found'
|
||||
)
|
||||
})
|
||||
|
||||
it("should emit user created events", async () => {
|
||||
const eventBusSpy = jest.spyOn(MockEventBusService.prototype, "emit")
|
||||
await service.create(defaultUserData)
|
||||
|
||||
jest.clearAllMocks()
|
||||
|
||||
await service.update([
|
||||
{
|
||||
id: "1",
|
||||
first_name: "John",
|
||||
},
|
||||
])
|
||||
|
||||
expect(eventBusSpy).toHaveBeenCalledTimes(1)
|
||||
expect(eventBusSpy).toHaveBeenCalledWith([
|
||||
expect.objectContaining({
|
||||
body: expect.objectContaining({
|
||||
data: { id: "1" },
|
||||
}),
|
||||
eventName: UserEvents.updated,
|
||||
}),
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe("create", () => {
|
||||
it("should create a user successfully", async () => {
|
||||
await service.create(defaultUserData)
|
||||
|
||||
const [User, count] = await service.listAndCount({
|
||||
id: ["1"],
|
||||
})
|
||||
|
||||
expect(count).toEqual(1)
|
||||
expect(User[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
id: "1",
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it("should emit user created events", async () => {
|
||||
const eventBusSpy = jest.spyOn(MockEventBusService.prototype, "emit")
|
||||
await service.create(defaultUserData)
|
||||
|
||||
expect(eventBusSpy).toHaveBeenCalledTimes(1)
|
||||
expect(eventBusSpy).toHaveBeenCalledWith([
|
||||
expect.objectContaining({
|
||||
body: expect.objectContaining({
|
||||
data: { id: "1" },
|
||||
}),
|
||||
eventName: UserEvents.created,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
body: expect.objectContaining({
|
||||
data: { id: "2" },
|
||||
}),
|
||||
eventName: UserEvents.created,
|
||||
}),
|
||||
])
|
||||
})
|
||||
})
|
||||
})
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,20 @@
|
||||
module.exports = {
|
||||
moduleNameMapper: {
|
||||
"^@models": "<rootDir>/src/models",
|
||||
"^@services": "<rootDir>/src/services",
|
||||
"^@repositories": "<rootDir>/src/repositories",
|
||||
"^@types": "<rootDir>/src/types",
|
||||
},
|
||||
transform: {
|
||||
"^.+\\.[jt]s?$": [
|
||||
"ts-jest",
|
||||
{
|
||||
tsconfig: "tsconfig.spec.json",
|
||||
isolatedModules: true,
|
||||
},
|
||||
],
|
||||
},
|
||||
testEnvironment: `node`,
|
||||
moduleFileExtensions: [`js`, `ts`],
|
||||
modulePathIgnorePatterns: ["dist/"],
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import * as entities from "./src/models"
|
||||
import { TSMigrationGenerator } from "@medusajs/utils"
|
||||
|
||||
module.exports = {
|
||||
entities: Object.values(entities),
|
||||
schema: "public",
|
||||
clientUrl: "postgres://postgres@localhost/medusa-user",
|
||||
type: "postgresql",
|
||||
migrations: {
|
||||
generator: TSMigrationGenerator,
|
||||
},
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
{
|
||||
"name": "@medusajs/user",
|
||||
"version": "0.0.3",
|
||||
"description": "Medusa Users module",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">=16"
|
||||
},
|
||||
"bin": {
|
||||
"medusa-user-seed": "dist/scripts/bin/run-seed.js"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/medusajs/medusa",
|
||||
"directory": "packages/user"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
},
|
||||
"author": "Medusa",
|
||||
"license": "MIT",
|
||||
"scripts": {
|
||||
"watch": "tsc --build --watch",
|
||||
"watch:test": "tsc --build tsconfig.spec.json --watch",
|
||||
"prepublishOnly": "cross-env NODE_ENV=production tsc --build && tsc-alias -p tsconfig.json",
|
||||
"build": "rimraf dist && tsc --build && tsc-alias -p tsconfig.json",
|
||||
"test": "jest --runInBand --passWithNoTests --bail --forceExit -- src",
|
||||
"test:integration": "jest --forceExit -- integration-tests/**/__tests__/**/*.ts",
|
||||
"migration:generate": " MIKRO_ORM_CLI=./mikro-orm.config.dev.ts mikro-orm migration:generate",
|
||||
"migration:initial": " MIKRO_ORM_CLI=./mikro-orm.config.dev.ts mikro-orm migration:create --initial",
|
||||
"migration:create": " MIKRO_ORM_CLI=./mikro-orm.config.dev.ts mikro-orm migration:create",
|
||||
"migration:up": " MIKRO_ORM_CLI=./mikro-orm.config.dev.ts mikro-orm migration:up",
|
||||
"orm:cache:clear": " MIKRO_ORM_CLI=./mikro-orm.config.dev.ts mikro-orm cache:clear"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@mikro-orm/cli": "5.9.7",
|
||||
"cross-env": "^5.2.1",
|
||||
"jest": "^29.6.3",
|
||||
"medusa-test-utils": "^1.1.43",
|
||||
"rimraf": "^3.0.2",
|
||||
"ts-jest": "^29.1.1",
|
||||
"ts-node": "^10.9.1",
|
||||
"tsc-alias": "^1.8.6",
|
||||
"typescript": "^5.1.6"
|
||||
},
|
||||
"dependencies": {
|
||||
"@medusajs/modules-sdk": "^1.12.10",
|
||||
"@medusajs/types": "^1.11.15",
|
||||
"@medusajs/utils": "^1.11.8",
|
||||
"@mikro-orm/core": "5.9.7",
|
||||
"@mikro-orm/migrations": "5.9.7",
|
||||
"@mikro-orm/postgresql": "5.9.7",
|
||||
"awilix": "^8.0.0",
|
||||
"dotenv": "^16.4.5",
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"knex": "2.4.2"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import {
|
||||
moduleDefinition,
|
||||
revertMigration,
|
||||
runMigrations,
|
||||
} from "./module-definition"
|
||||
|
||||
export default moduleDefinition
|
||||
export { revertMigration, runMigrations }
|
||||
|
||||
export * from "./initialize"
|
||||
export * from "./loaders"
|
||||
@@ -0,0 +1,31 @@
|
||||
import {
|
||||
ExternalModuleDeclaration,
|
||||
InternalModuleDeclaration,
|
||||
MODULE_PACKAGE_NAMES,
|
||||
MedusaModule,
|
||||
Modules,
|
||||
} from "@medusajs/modules-sdk"
|
||||
import { IUserModuleService, ModulesSdkTypes } from "@medusajs/types"
|
||||
|
||||
import { InitializeModuleInjectableDependencies } from "../types"
|
||||
import { moduleDefinition } from "../module-definition"
|
||||
|
||||
export const initialize = async (
|
||||
options?:
|
||||
| ModulesSdkTypes.ModuleBootstrapDeclaration
|
||||
| ModulesSdkTypes.ModuleServiceInitializeOptions
|
||||
| ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions,
|
||||
injectedDependencies?: InitializeModuleInjectableDependencies
|
||||
): Promise<IUserModuleService> => {
|
||||
const loaded = await MedusaModule.bootstrap<IUserModuleService>({
|
||||
moduleKey: Modules.USER,
|
||||
defaultPath: MODULE_PACKAGE_NAMES[Modules.USER],
|
||||
declaration: options as
|
||||
| InternalModuleDeclaration
|
||||
| ExternalModuleDeclaration,
|
||||
injectedDependencies,
|
||||
moduleExports: moduleDefinition,
|
||||
})
|
||||
|
||||
return loaded[Modules.USER]
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { Invite, User } from "@models"
|
||||
import { MapToConfig } from "@medusajs/utils"
|
||||
import { ModuleJoinerConfig } from "@medusajs/types"
|
||||
import { Modules } from "@medusajs/modules-sdk"
|
||||
|
||||
export const LinkableKeys = {
|
||||
user_id: User.name,
|
||||
invite_id: Invite.name,
|
||||
}
|
||||
|
||||
const entityLinkableKeysMap: MapToConfig = {}
|
||||
Object.entries(LinkableKeys).forEach(([key, value]) => {
|
||||
entityLinkableKeysMap[value] ??= []
|
||||
entityLinkableKeysMap[value].push({
|
||||
mapTo: key,
|
||||
valueFrom: key.split("_").pop()!,
|
||||
})
|
||||
})
|
||||
|
||||
export const entityNameToLinkableKeysMap: MapToConfig = entityLinkableKeysMap
|
||||
|
||||
export const joinerConfig: ModuleJoinerConfig = {
|
||||
serviceName: Modules.USER,
|
||||
primaryKeys: ["id"],
|
||||
linkableKeys: LinkableKeys,
|
||||
alias: [
|
||||
{
|
||||
name: ["user", "users"],
|
||||
args: {
|
||||
entity: User.name,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: ["invite", "invites"],
|
||||
args: {
|
||||
entity: Invite.name,
|
||||
methodSuffix: "Invites",
|
||||
},
|
||||
},
|
||||
],
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import * as UserModels from "../models"
|
||||
|
||||
import {
|
||||
InternalModuleDeclaration,
|
||||
LoaderOptions,
|
||||
Modules,
|
||||
} from "@medusajs/modules-sdk"
|
||||
|
||||
import { EntitySchema } from "@mikro-orm/core"
|
||||
import { ModulesSdkTypes } from "@medusajs/types"
|
||||
import { ModulesSdkUtils } from "@medusajs/utils"
|
||||
|
||||
export default async (
|
||||
{
|
||||
options,
|
||||
container,
|
||||
logger,
|
||||
}: LoaderOptions<
|
||||
| ModulesSdkTypes.ModuleServiceInitializeOptions
|
||||
| ModulesSdkTypes.ModuleServiceInitializeCustomDataLayerOptions
|
||||
>,
|
||||
moduleDeclaration?: InternalModuleDeclaration
|
||||
): Promise<void> => {
|
||||
const entities = Object.values(UserModels) as unknown as EntitySchema[]
|
||||
const pathToMigrations = __dirname + "/../migrations"
|
||||
|
||||
await ModulesSdkUtils.mikroOrmConnectionLoader({
|
||||
moduleName: Modules.USER,
|
||||
entities,
|
||||
container,
|
||||
options,
|
||||
moduleDeclaration,
|
||||
logger,
|
||||
pathToMigrations,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import { ModulesSdkUtils } from "@medusajs/utils"
|
||||
import * as ModuleModels from "@models"
|
||||
import * as ModuleRepositories from "@repositories"
|
||||
import * as ModuleServices from "@services"
|
||||
|
||||
export default ModulesSdkUtils.moduleContainerLoaderFactory({
|
||||
moduleModels: ModuleModels,
|
||||
moduleRepositories: ModuleRepositories,
|
||||
moduleServices: ModuleServices,
|
||||
})
|
||||
@@ -0,0 +1,2 @@
|
||||
export * from "./connection"
|
||||
export * from "./container"
|
||||
@@ -0,0 +1,270 @@
|
||||
{
|
||||
"namespaces": [
|
||||
"public"
|
||||
],
|
||||
"name": "public",
|
||||
"tables": [
|
||||
{
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": false,
|
||||
"mappedType": "text"
|
||||
},
|
||||
"email": {
|
||||
"name": "email",
|
||||
"type": "text",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": false,
|
||||
"mappedType": "text"
|
||||
},
|
||||
"accepted": {
|
||||
"name": "accepted",
|
||||
"type": "boolean",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": false,
|
||||
"default": "false",
|
||||
"mappedType": "boolean"
|
||||
},
|
||||
"token": {
|
||||
"name": "token",
|
||||
"type": "text",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": false,
|
||||
"mappedType": "text"
|
||||
},
|
||||
"expires_at": {
|
||||
"name": "expires_at",
|
||||
"type": "timestamptz",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": false,
|
||||
"length": 6,
|
||||
"mappedType": "datetime"
|
||||
},
|
||||
"metadata": {
|
||||
"name": "metadata",
|
||||
"type": "jsonb",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": true,
|
||||
"mappedType": "json"
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamptz",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": false,
|
||||
"length": 6,
|
||||
"default": "now()",
|
||||
"mappedType": "datetime"
|
||||
},
|
||||
"updated_at": {
|
||||
"name": "updated_at",
|
||||
"type": "timestamptz",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": false,
|
||||
"length": 6,
|
||||
"default": "now()",
|
||||
"mappedType": "datetime"
|
||||
},
|
||||
"deleted_at": {
|
||||
"name": "deleted_at",
|
||||
"type": "timestamptz",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": true,
|
||||
"length": 6,
|
||||
"mappedType": "datetime"
|
||||
}
|
||||
},
|
||||
"name": "invite",
|
||||
"schema": "public",
|
||||
"indexes": [
|
||||
{
|
||||
"keyName": "IDX_invite_email",
|
||||
"columnNames": [
|
||||
"email"
|
||||
],
|
||||
"composite": false,
|
||||
"primary": false,
|
||||
"unique": false,
|
||||
"expression": "CREATE UNIQUE INDEX IF NOT EXISTS \"IDX_invite_email\" ON \"invite\" (email) WHERE deleted_at IS NULL"
|
||||
},
|
||||
{
|
||||
"keyName": "IDX_invite_token",
|
||||
"columnNames": [
|
||||
"token"
|
||||
],
|
||||
"composite": false,
|
||||
"primary": false,
|
||||
"unique": false,
|
||||
"expression": "CREATE INDEX IF NOT EXISTS \"IDX_invite_token\" ON \"invite\" (token) WHERE deleted_at IS NULL"
|
||||
},
|
||||
{
|
||||
"keyName": "IDX_invite_deleted_at",
|
||||
"columnNames": [
|
||||
"deleted_at"
|
||||
],
|
||||
"composite": false,
|
||||
"primary": false,
|
||||
"unique": false,
|
||||
"expression": "CREATE INDEX IF NOT EXISTS \"IDX_invite_token\" ON \"invite\" (deleted_at) WHERE deleted_at IS NOT NULL"
|
||||
},
|
||||
{
|
||||
"keyName": "invite_pkey",
|
||||
"columnNames": [
|
||||
"id"
|
||||
],
|
||||
"composite": false,
|
||||
"primary": true,
|
||||
"unique": true
|
||||
}
|
||||
],
|
||||
"checks": [],
|
||||
"foreignKeys": {}
|
||||
},
|
||||
{
|
||||
"columns": {
|
||||
"id": {
|
||||
"name": "id",
|
||||
"type": "text",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": false,
|
||||
"mappedType": "text"
|
||||
},
|
||||
"first_name": {
|
||||
"name": "first_name",
|
||||
"type": "text",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": true,
|
||||
"mappedType": "text"
|
||||
},
|
||||
"last_name": {
|
||||
"name": "last_name",
|
||||
"type": "text",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": true,
|
||||
"mappedType": "text"
|
||||
},
|
||||
"email": {
|
||||
"name": "email",
|
||||
"type": "text",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": false,
|
||||
"mappedType": "text"
|
||||
},
|
||||
"avatar_url": {
|
||||
"name": "avatar_url",
|
||||
"type": "text",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": true,
|
||||
"mappedType": "text"
|
||||
},
|
||||
"metadata": {
|
||||
"name": "metadata",
|
||||
"type": "jsonb",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": true,
|
||||
"mappedType": "json"
|
||||
},
|
||||
"created_at": {
|
||||
"name": "created_at",
|
||||
"type": "timestamptz",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": false,
|
||||
"length": 6,
|
||||
"default": "now()",
|
||||
"mappedType": "datetime"
|
||||
},
|
||||
"updated_at": {
|
||||
"name": "updated_at",
|
||||
"type": "timestamptz",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": false,
|
||||
"length": 6,
|
||||
"default": "now()",
|
||||
"mappedType": "datetime"
|
||||
},
|
||||
"deleted_at": {
|
||||
"name": "deleted_at",
|
||||
"type": "timestamptz",
|
||||
"unsigned": false,
|
||||
"autoincrement": false,
|
||||
"primary": false,
|
||||
"nullable": true,
|
||||
"length": 6,
|
||||
"mappedType": "datetime"
|
||||
}
|
||||
},
|
||||
"name": "user",
|
||||
"schema": "public",
|
||||
"indexes": [
|
||||
{
|
||||
"keyName": "IDX_user_email",
|
||||
"columnNames": [
|
||||
"email"
|
||||
],
|
||||
"composite": false,
|
||||
"primary": false,
|
||||
"unique": false,
|
||||
"expression": "CREATE INDEX IF NOT EXISTS \"IDX_user_email\" ON \"user\" (email) WHERE deleted_at IS NULL"
|
||||
},
|
||||
{
|
||||
"keyName": "IDX_user_deleted_at",
|
||||
"columnNames": [
|
||||
"deleted_at"
|
||||
],
|
||||
"composite": false,
|
||||
"primary": false,
|
||||
"unique": false,
|
||||
"expression": "CREATE INDEX IF NOT EXISTS \"IDX_user_deleted_at\" ON \"user\" (deleted_at) WHERE deleted_at IS NOT NULL"
|
||||
},
|
||||
{
|
||||
"keyName": "user_pkey",
|
||||
"columnNames": [
|
||||
"id"
|
||||
],
|
||||
"composite": false,
|
||||
"primary": true,
|
||||
"unique": true
|
||||
}
|
||||
],
|
||||
"checks": [],
|
||||
"foreignKeys": {}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { generatePostgresAlterColummnIfExistStatement } from "@medusajs/utils"
|
||||
import { Migration } from "@mikro-orm/migrations"
|
||||
|
||||
export class Migration20240214033943 extends Migration {
|
||||
async up(): Promise<void> {
|
||||
this.addSql(
|
||||
'create table if not exists "invite" ("id" text not null, "email" text not null, "accepted" boolean not null default false, "token" text not null, "expires_at" timestamptz not null, "metadata" jsonb null, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null, constraint "invite_pkey" primary key ("id"));'
|
||||
)
|
||||
this.addSql(
|
||||
'alter table "invite" add column if not exists "email" text not null;'
|
||||
)
|
||||
|
||||
this.addSql(
|
||||
generatePostgresAlterColummnIfExistStatement(
|
||||
"invite",
|
||||
["user_email"],
|
||||
"DROP NOT NULL"
|
||||
)
|
||||
)
|
||||
|
||||
this.addSql(
|
||||
'CREATE UNIQUE INDEX IF NOT EXISTS "IDX_invite_email" ON "invite" (email) WHERE deleted_at IS NULL;'
|
||||
)
|
||||
|
||||
this.addSql(
|
||||
'CREATE INDEX IF NOT EXISTS "IDX_invite_token" ON "invite" (token) WHERE deleted_at IS NULL;'
|
||||
)
|
||||
this.addSql(
|
||||
'CREATE INDEX IF NOT EXISTS "IDX_invite_deleted_at" ON "invite" (deleted_at) WHERE deleted_at IS NOT NULL;'
|
||||
)
|
||||
|
||||
this.addSql(
|
||||
'create table if not exists "user" ("id" text not null, "first_name" text null, "last_name" text null, "email" text not null, "avatar_url" text null, "metadata" jsonb null, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null, constraint "user_pkey" primary key ("id"));'
|
||||
)
|
||||
|
||||
this.addSql(
|
||||
'alter table "user" add column if not exists "avatar_url" text null;'
|
||||
)
|
||||
|
||||
this.addSql(
|
||||
'CREATE INDEX IF NOT EXISTS "IDX_user_email" ON "user" (email) WHERE deleted_at IS NULL;'
|
||||
)
|
||||
this.addSql(
|
||||
'CREATE INDEX IF NOT EXISTS "IDX_user_deleted_at" ON "user" (deleted_at) WHERE deleted_at IS NOT NULL;'
|
||||
)
|
||||
}
|
||||
|
||||
async down(): Promise<void> {
|
||||
this.addSql('drop table if exists "invite" cascade;')
|
||||
|
||||
this.addSql('drop table if exists "user" cascade;')
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export { default as User } from "./user"
|
||||
export { default as Invite } from "./invite"
|
||||
@@ -0,0 +1,112 @@
|
||||
import {
|
||||
BeforeCreate,
|
||||
Entity,
|
||||
Filter,
|
||||
Index,
|
||||
OnInit,
|
||||
OptionalProps,
|
||||
PrimaryKey,
|
||||
Property,
|
||||
} from "@mikro-orm/core"
|
||||
|
||||
import { DAL } from "@medusajs/types"
|
||||
import {
|
||||
DALUtils,
|
||||
createPsqlIndexStatementHelper,
|
||||
generateEntityId,
|
||||
Searchable,
|
||||
} from "@medusajs/utils"
|
||||
|
||||
const inviteEmailIndexName = "IDX_invite_email"
|
||||
const inviteEmailIndexStatement = createPsqlIndexStatementHelper({
|
||||
name: inviteEmailIndexName,
|
||||
tableName: "invite",
|
||||
columns: "email",
|
||||
where: "deleted_at IS NULL",
|
||||
unique: true,
|
||||
}).expression
|
||||
|
||||
const inviteTokenIndexName = "IDX_invite_token"
|
||||
const inviteTokenIndexStatement = createPsqlIndexStatementHelper({
|
||||
name: inviteTokenIndexName,
|
||||
tableName: "invite",
|
||||
columns: "token",
|
||||
where: "deleted_at IS NULL",
|
||||
}).expression
|
||||
|
||||
const inviteDeletedAtIndexName = "IDX_invite_deleted_at"
|
||||
const inviteDeletedAtIndexStatement = createPsqlIndexStatementHelper({
|
||||
name: inviteDeletedAtIndexName,
|
||||
tableName: "invite",
|
||||
columns: "deleted_at",
|
||||
where: "deleted_at IS NOT NULL",
|
||||
}).expression
|
||||
|
||||
type OptionalFields =
|
||||
| "metadata"
|
||||
| "accepted"
|
||||
| DAL.SoftDeletableEntityDateColumns
|
||||
@Entity({ tableName: "invite" })
|
||||
@Filter(DALUtils.mikroOrmSoftDeletableFilterOptions)
|
||||
export default class Invite {
|
||||
[OptionalProps]: OptionalFields
|
||||
|
||||
@PrimaryKey({ columnType: "text" })
|
||||
id: string
|
||||
|
||||
@Index({
|
||||
name: inviteEmailIndexName,
|
||||
expression: inviteEmailIndexStatement,
|
||||
})
|
||||
@Searchable()
|
||||
@Property({ columnType: "text" })
|
||||
email: string
|
||||
|
||||
@Property({ columnType: "boolean" })
|
||||
accepted: boolean = false
|
||||
|
||||
@Index({
|
||||
name: inviteTokenIndexName,
|
||||
expression: inviteTokenIndexStatement,
|
||||
})
|
||||
@Property({ columnType: "text" })
|
||||
token: string
|
||||
|
||||
@Property({ columnType: "timestamptz" })
|
||||
expires_at: Date
|
||||
|
||||
@Property({ columnType: "jsonb", nullable: true })
|
||||
metadata: Record<string, unknown> | null = null
|
||||
|
||||
@Property({
|
||||
onCreate: () => new Date(),
|
||||
columnType: "timestamptz",
|
||||
defaultRaw: "now()",
|
||||
})
|
||||
created_at: Date
|
||||
|
||||
@Property({
|
||||
onCreate: () => new Date(),
|
||||
onUpdate: () => new Date(),
|
||||
columnType: "timestamptz",
|
||||
defaultRaw: "now()",
|
||||
})
|
||||
updated_at: Date
|
||||
|
||||
@Index({
|
||||
name: inviteDeletedAtIndexName,
|
||||
expression: inviteDeletedAtIndexStatement,
|
||||
})
|
||||
@Property({ columnType: "timestamptz", nullable: true })
|
||||
deleted_at: Date | null = null
|
||||
|
||||
@OnInit()
|
||||
onInit() {
|
||||
this.id = generateEntityId(this.id, "invite")
|
||||
}
|
||||
|
||||
@BeforeCreate()
|
||||
beforeCreate() {
|
||||
this.id = generateEntityId(this.id, "invite")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
import {
|
||||
BeforeCreate,
|
||||
Entity,
|
||||
Filter,
|
||||
Index,
|
||||
OnInit,
|
||||
OptionalProps,
|
||||
PrimaryKey,
|
||||
Property,
|
||||
} from "@mikro-orm/core"
|
||||
|
||||
import { DAL } from "@medusajs/types"
|
||||
import {
|
||||
DALUtils,
|
||||
createPsqlIndexStatementHelper,
|
||||
generateEntityId,
|
||||
Searchable,
|
||||
} from "@medusajs/utils"
|
||||
|
||||
const userEmailIndexName = "IDX_user_email"
|
||||
const userEmailIndexStatement = createPsqlIndexStatementHelper({
|
||||
name: userEmailIndexName,
|
||||
tableName: "user",
|
||||
columns: "email",
|
||||
where: "deleted_at IS NULL",
|
||||
}).expression
|
||||
|
||||
const userDeletedAtIndexName = "IDX_user_deleted_at"
|
||||
const userDeletedAtIndexStatement = createPsqlIndexStatementHelper({
|
||||
name: userDeletedAtIndexName,
|
||||
tableName: "user",
|
||||
columns: "deleted_at",
|
||||
where: "deleted_at IS NOT NULL",
|
||||
}).expression
|
||||
|
||||
type OptionalFields =
|
||||
| "first_name"
|
||||
| "last_name"
|
||||
| "metadata"
|
||||
| "avatar_url"
|
||||
| DAL.SoftDeletableEntityDateColumns
|
||||
|
||||
@Entity()
|
||||
@Filter(DALUtils.mikroOrmSoftDeletableFilterOptions)
|
||||
export default class User {
|
||||
[OptionalProps]?: OptionalFields
|
||||
|
||||
@PrimaryKey({ columnType: "text" })
|
||||
id!: string
|
||||
|
||||
@Searchable()
|
||||
@Property({ columnType: "text", nullable: true })
|
||||
first_name: string | null = null
|
||||
|
||||
@Searchable()
|
||||
@Property({ columnType: "text", nullable: true })
|
||||
last_name: string | null = null
|
||||
|
||||
@Index({
|
||||
name: userEmailIndexName,
|
||||
expression: userEmailIndexStatement,
|
||||
})
|
||||
@Searchable()
|
||||
@Property({ columnType: "text" })
|
||||
email: string
|
||||
|
||||
@Property({ columnType: "text", nullable: true })
|
||||
avatar_url: string | null = null
|
||||
|
||||
@Property({ columnType: "jsonb", nullable: true })
|
||||
metadata: Record<string, unknown> | null = null
|
||||
|
||||
@Property({
|
||||
onCreate: () => new Date(),
|
||||
columnType: "timestamptz",
|
||||
defaultRaw: "now()",
|
||||
})
|
||||
created_at: Date
|
||||
|
||||
@Property({
|
||||
onCreate: () => new Date(),
|
||||
onUpdate: () => new Date(),
|
||||
columnType: "timestamptz",
|
||||
defaultRaw: "now()",
|
||||
})
|
||||
updated_at: Date
|
||||
|
||||
@Index({
|
||||
name: userDeletedAtIndexName,
|
||||
expression: userDeletedAtIndexStatement,
|
||||
})
|
||||
@Property({ columnType: "timestamptz", nullable: true })
|
||||
deleted_at?: Date | null = null
|
||||
|
||||
@BeforeCreate()
|
||||
onCreate() {
|
||||
this.id = generateEntityId(this.id, "user")
|
||||
}
|
||||
|
||||
@OnInit()
|
||||
onInit() {
|
||||
this.id = generateEntityId(this.id, "user")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import * as Models from "@models"
|
||||
|
||||
import { UserModuleService } from "@services"
|
||||
import { ModuleExports } from "@medusajs/types"
|
||||
import { Modules } from "@medusajs/modules-sdk"
|
||||
import { ModulesSdkUtils } from "@medusajs/utils"
|
||||
import loadConnection from "./loaders/connection"
|
||||
import loadContainer from "./loaders/container"
|
||||
|
||||
const migrationScriptOptions = {
|
||||
moduleName: Modules.USER,
|
||||
models: Models,
|
||||
pathToMigrations: __dirname + "/migrations",
|
||||
}
|
||||
|
||||
export const runMigrations = ModulesSdkUtils.buildMigrationScript(
|
||||
migrationScriptOptions
|
||||
)
|
||||
export const revertMigration = ModulesSdkUtils.buildRevertMigrationScript(
|
||||
migrationScriptOptions
|
||||
)
|
||||
|
||||
const service = UserModuleService
|
||||
const loaders = [loadContainer, loadConnection] as any
|
||||
|
||||
export const moduleDefinition: ModuleExports = {
|
||||
service,
|
||||
loaders,
|
||||
runMigrations,
|
||||
revertMigration,
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export { MikroOrmBaseRepository as BaseRepository } from "@medusajs/utils"
|
||||
@@ -0,0 +1,19 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import { EOL } from "os"
|
||||
import { run } from "../seed"
|
||||
|
||||
const args = process.argv
|
||||
const path = args.pop() as string
|
||||
|
||||
export default (async () => {
|
||||
const { config } = await import("dotenv")
|
||||
config()
|
||||
if (!path) {
|
||||
throw new Error(
|
||||
`filePath is required.${EOL}Example: medusa-user-seed <filePath>`
|
||||
)
|
||||
}
|
||||
|
||||
await run({ path })
|
||||
})()
|
||||
@@ -0,0 +1,58 @@
|
||||
import * as UserModels from "@models"
|
||||
|
||||
import { DALUtils, ModulesSdkUtils } from "@medusajs/utils"
|
||||
import { LoaderOptions, Logger, ModulesSdkTypes } from "@medusajs/types"
|
||||
|
||||
import { EOL } from "os"
|
||||
import { EntitySchema } from "@mikro-orm/core"
|
||||
import { Modules } from "@medusajs/modules-sdk"
|
||||
import { resolve } from "path"
|
||||
|
||||
export async function run({
|
||||
options,
|
||||
logger,
|
||||
path,
|
||||
}: Partial<
|
||||
Pick<
|
||||
LoaderOptions<ModulesSdkTypes.ModuleServiceInitializeOptions>,
|
||||
"options" | "logger"
|
||||
>
|
||||
> & {
|
||||
path: string
|
||||
}) {
|
||||
logger ??= console as unknown as Logger
|
||||
|
||||
logger.info(`Loading seed data from ${path}...`)
|
||||
|
||||
const { userData } = await import(resolve(process.cwd(), path)).catch((e) => {
|
||||
logger?.error(
|
||||
`Failed to load seed data from ${path}. Please, provide a relative path and check that you export the following: userData.${EOL}${e}`
|
||||
)
|
||||
throw e
|
||||
})
|
||||
|
||||
const dbData = ModulesSdkUtils.loadDatabaseConfig(Modules.USER, options)!
|
||||
const entities = Object.values(UserModels) as unknown as EntitySchema[]
|
||||
const pathToMigrations = __dirname + "/../migrations"
|
||||
|
||||
const orm = await DALUtils.mikroOrmCreateConnection(
|
||||
dbData,
|
||||
entities,
|
||||
pathToMigrations
|
||||
)
|
||||
|
||||
const manager = orm.em.fork()
|
||||
|
||||
try {
|
||||
logger.info("Seeding user data..")
|
||||
|
||||
// TODO: implement user seed data
|
||||
// await createUsers(manager, usersData)
|
||||
} catch (e) {
|
||||
logger.error(
|
||||
`Failed to insert the seed data in the PostgreSQL database ${dbData.clientUrl}.${EOL}${e}`
|
||||
)
|
||||
}
|
||||
|
||||
await orm.close(true)
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
export { default as UserModuleService } from "./user-module"
|
||||
export { default as InviteService } from "./invite"
|
||||
@@ -0,0 +1,184 @@
|
||||
import * as crypto from "crypto"
|
||||
|
||||
import { Context, DAL } from "@medusajs/types"
|
||||
import {
|
||||
InjectTransactionManager,
|
||||
MedusaError,
|
||||
ModulesSdkUtils,
|
||||
arrayDifference,
|
||||
} from "@medusajs/utils"
|
||||
import jwt, { JwtPayload } from "jsonwebtoken"
|
||||
|
||||
import { Invite } from "@models"
|
||||
import { InviteServiceTypes } from "@types"
|
||||
|
||||
type InjectedDependencies = {
|
||||
inviteRepository: DAL.RepositoryService
|
||||
}
|
||||
|
||||
// 1 day
|
||||
const DEFAULT_VALID_INVITE_DURATION = 60 * 60 * 24 * 1000
|
||||
|
||||
export default class InviteService<
|
||||
TEntity extends Invite = Invite
|
||||
> extends ModulesSdkUtils.internalModuleServiceFactory<InjectedDependencies>(
|
||||
Invite
|
||||
)<TEntity> {
|
||||
// eslint-disable-next-line max-len
|
||||
protected readonly inviteRepository_: DAL.RepositoryService<TEntity>
|
||||
protected options_: { jwt_secret: string; valid_duration: number } | undefined
|
||||
|
||||
constructor(container: InjectedDependencies) {
|
||||
super(container)
|
||||
this.inviteRepository_ = container.inviteRepository
|
||||
}
|
||||
|
||||
public withModuleOptions(options: any) {
|
||||
const service = new InviteService<TEntity>(this.__container__)
|
||||
|
||||
service.options_ = options
|
||||
|
||||
return service
|
||||
}
|
||||
|
||||
private getOption(key: string) {
|
||||
if (!this.options_) {
|
||||
throw new MedusaError(
|
||||
MedusaError.Types.UNEXPECTED_STATE,
|
||||
`Options are not configured for InviteService, call "withModuleOptions" and provide options`
|
||||
)
|
||||
}
|
||||
return this.options_[key]
|
||||
}
|
||||
|
||||
create(
|
||||
data: InviteServiceTypes.CreateInviteDTO,
|
||||
context?: Context
|
||||
): Promise<TEntity>
|
||||
create(
|
||||
data: InviteServiceTypes.CreateInviteDTO[],
|
||||
context?: Context
|
||||
): Promise<TEntity[]>
|
||||
|
||||
@InjectTransactionManager("inviteRepository_")
|
||||
async create(
|
||||
data:
|
||||
| InviteServiceTypes.CreateInviteDTO
|
||||
| InviteServiceTypes.CreateInviteDTO[],
|
||||
context: Context = {}
|
||||
): Promise<TEntity | TEntity[]> {
|
||||
const data_ = Array.isArray(data) ? data : [data]
|
||||
|
||||
const invites = await super.create(data_, context)
|
||||
|
||||
const expiresIn: number = this.getValidDuration()
|
||||
|
||||
const updates = invites.map((invite) => {
|
||||
return {
|
||||
id: invite.id,
|
||||
expires_at: new Date().setMilliseconds(
|
||||
new Date().getMilliseconds() + expiresIn
|
||||
),
|
||||
token: this.generateToken({ id: invite.id }),
|
||||
}
|
||||
})
|
||||
|
||||
return await super.update(updates, context)
|
||||
}
|
||||
|
||||
@InjectTransactionManager("inviteRepository_")
|
||||
async refreshInviteTokens(
|
||||
inviteIds: string[],
|
||||
context: Context = {}
|
||||
): Promise<TEntity[]> {
|
||||
const [invites, count] = await super.listAndCount(
|
||||
{ id: inviteIds },
|
||||
{},
|
||||
context
|
||||
)
|
||||
|
||||
if (count !== inviteIds.length) {
|
||||
const missing = arrayDifference(
|
||||
inviteIds,
|
||||
invites.map((invite) => invite.id)
|
||||
)
|
||||
|
||||
if (missing.length > 0) {
|
||||
throw new MedusaError(
|
||||
MedusaError.Types.INVALID_DATA,
|
||||
`The following invites do not exist: ${missing.join(", ")}`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const expiresIn: number = this.getValidDuration()
|
||||
|
||||
const updates = invites.map((invite) => {
|
||||
return {
|
||||
id: invite.id,
|
||||
expires_at: new Date().setMilliseconds(
|
||||
new Date().getMilliseconds() + expiresIn
|
||||
),
|
||||
token: this.generateToken({ id: invite.id }),
|
||||
}
|
||||
})
|
||||
|
||||
return await super.update(updates, context)
|
||||
}
|
||||
|
||||
@InjectTransactionManager("inviteRepository_")
|
||||
async validateInviteToken(
|
||||
token: string,
|
||||
context?: Context
|
||||
): Promise<TEntity> {
|
||||
const decoded = this.validateToken(token)
|
||||
|
||||
const invite = await super.retrieve(decoded.payload.id, {}, context)
|
||||
|
||||
if (invite.expires_at < new Date()) {
|
||||
throw new MedusaError(
|
||||
MedusaError.Types.INVALID_DATA,
|
||||
"The invite has expired"
|
||||
)
|
||||
}
|
||||
|
||||
return invite
|
||||
}
|
||||
|
||||
private generateToken(data: any): string {
|
||||
const jwtSecret: string = this.getOption("jwt_secret")
|
||||
const expiresIn: number = this.getValidDuration() / 1000
|
||||
|
||||
if (!jwtSecret) {
|
||||
throw new MedusaError(
|
||||
MedusaError.Types.INVALID_DATA,
|
||||
"No jwt_secret was provided in the UserModule's options. Please add one."
|
||||
)
|
||||
}
|
||||
|
||||
return jwt.sign(data, jwtSecret, {
|
||||
jwtid: crypto.randomUUID(),
|
||||
expiresIn,
|
||||
})
|
||||
}
|
||||
|
||||
private getValidDuration(): number {
|
||||
return (
|
||||
parseInt(this.getOption("valid_duration")) ||
|
||||
DEFAULT_VALID_INVITE_DURATION
|
||||
)
|
||||
}
|
||||
|
||||
private validateToken(data: any): JwtPayload {
|
||||
const jwtSecret = this.getOption("jwt_secret")
|
||||
|
||||
if (!jwtSecret) {
|
||||
throw new MedusaError(
|
||||
MedusaError.Types.INVALID_DATA,
|
||||
"No jwt_secret was provided in the UserModule's options. Please add one."
|
||||
)
|
||||
}
|
||||
|
||||
return jwt.verify(data, jwtSecret, { complete: true })
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
import {
|
||||
Context,
|
||||
DAL,
|
||||
InternalModuleDeclaration,
|
||||
ModuleJoinerConfig,
|
||||
UserTypes,
|
||||
ModulesSdkTypes,
|
||||
IEventBusModuleService,
|
||||
} from "@medusajs/types"
|
||||
import {
|
||||
EmitEvents,
|
||||
InjectTransactionManager,
|
||||
MedusaContext,
|
||||
ModulesSdkUtils,
|
||||
InjectManager,
|
||||
CommonEvents,
|
||||
UserEvents,
|
||||
} from "@medusajs/utils"
|
||||
import { entityNameToLinkableKeysMap, joinerConfig } from "../joiner-config"
|
||||
|
||||
import { Invite, User } from "@models"
|
||||
import InviteService from "./invite"
|
||||
|
||||
type InjectedDependencies = {
|
||||
baseRepository: DAL.RepositoryService
|
||||
userService: ModulesSdkTypes.InternalModuleService<any>
|
||||
inviteService: InviteService<any>
|
||||
eventBusModuleService: IEventBusModuleService
|
||||
}
|
||||
|
||||
const generateMethodForModels = [Invite]
|
||||
|
||||
export default class UserModuleService<
|
||||
TUser extends User = User,
|
||||
TInvite extends Invite = Invite
|
||||
>
|
||||
extends ModulesSdkUtils.abstractModuleServiceFactory<
|
||||
InjectedDependencies,
|
||||
UserTypes.UserDTO,
|
||||
{
|
||||
Invite: {
|
||||
dto: UserTypes.InviteDTO
|
||||
}
|
||||
}
|
||||
>(User, generateMethodForModels, entityNameToLinkableKeysMap)
|
||||
implements UserTypes.IUserModuleService
|
||||
{
|
||||
__joinerConfig(): ModuleJoinerConfig {
|
||||
return joinerConfig
|
||||
}
|
||||
|
||||
protected baseRepository_: DAL.RepositoryService
|
||||
|
||||
protected readonly userService_: ModulesSdkTypes.InternalModuleService<TUser>
|
||||
protected readonly inviteService_: InviteService<TInvite>
|
||||
|
||||
constructor(
|
||||
{ userService, inviteService, baseRepository }: InjectedDependencies,
|
||||
protected readonly moduleDeclaration: InternalModuleDeclaration
|
||||
) {
|
||||
// @ts-ignore
|
||||
super(...arguments)
|
||||
|
||||
this.baseRepository_ = baseRepository
|
||||
this.userService_ = userService
|
||||
this.inviteService_ = inviteService.withModuleOptions(
|
||||
this.moduleDeclaration
|
||||
)
|
||||
}
|
||||
|
||||
@InjectTransactionManager("baseRepository_")
|
||||
async validateInviteToken(
|
||||
token: string,
|
||||
@MedusaContext() sharedContext: Context = {}
|
||||
): Promise<UserTypes.InviteDTO> {
|
||||
const invite = await this.inviteService_.validateInviteToken(
|
||||
token,
|
||||
sharedContext
|
||||
)
|
||||
|
||||
return await this.baseRepository_.serialize<UserTypes.InviteDTO>(invite, {
|
||||
populate: true,
|
||||
})
|
||||
}
|
||||
|
||||
@InjectManager("baseRepository_")
|
||||
@EmitEvents()
|
||||
async refreshInviteTokens(
|
||||
inviteIds: string[],
|
||||
@MedusaContext() sharedContext: Context = {}
|
||||
): Promise<UserTypes.InviteDTO[]> {
|
||||
const invites = await this.refreshInviteTokens_(inviteIds, sharedContext)
|
||||
|
||||
sharedContext.messageAggregator?.saveRawMessageData(
|
||||
invites.map((invite) => ({
|
||||
eventName: UserEvents.invite_token_generated,
|
||||
metadata: {
|
||||
service: this.constructor.name,
|
||||
action: "token_generated",
|
||||
object: "invite",
|
||||
},
|
||||
data: { id: invite.id },
|
||||
}))
|
||||
)
|
||||
|
||||
return await this.baseRepository_.serialize<UserTypes.InviteDTO[]>(
|
||||
invites,
|
||||
{
|
||||
populate: true,
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
@InjectTransactionManager("baseRepository_")
|
||||
async refreshInviteTokens_(
|
||||
inviteIds: string[],
|
||||
@MedusaContext() sharedContext: Context = {}
|
||||
) {
|
||||
return await this.inviteService_.refreshInviteTokens(
|
||||
inviteIds,
|
||||
sharedContext
|
||||
)
|
||||
}
|
||||
|
||||
create(
|
||||
data: UserTypes.CreateUserDTO[],
|
||||
sharedContext?: Context
|
||||
): Promise<UserTypes.UserDTO[]>
|
||||
create(
|
||||
data: UserTypes.CreateUserDTO,
|
||||
sharedContext?: Context
|
||||
): Promise<UserTypes.UserDTO>
|
||||
|
||||
@InjectManager("baseRepository_")
|
||||
@EmitEvents()
|
||||
async create(
|
||||
data: UserTypes.CreateUserDTO[] | UserTypes.CreateUserDTO,
|
||||
@MedusaContext() sharedContext: Context = {}
|
||||
): Promise<UserTypes.UserDTO | UserTypes.UserDTO[]> {
|
||||
const input = Array.isArray(data) ? data : [data]
|
||||
|
||||
const users = await this.userService_.create(input, sharedContext)
|
||||
|
||||
const serializedUsers = await this.baseRepository_.serialize<
|
||||
UserTypes.UserDTO[] | UserTypes.UserDTO
|
||||
>(users, {
|
||||
populate: true,
|
||||
})
|
||||
|
||||
sharedContext.messageAggregator?.saveRawMessageData(
|
||||
users.map((user) => ({
|
||||
eventName: UserEvents.created,
|
||||
metadata: {
|
||||
service: this.constructor.name,
|
||||
action: CommonEvents.CREATED,
|
||||
object: "user",
|
||||
},
|
||||
data: { id: user.id },
|
||||
}))
|
||||
)
|
||||
|
||||
return Array.isArray(data) ? serializedUsers : serializedUsers[0]
|
||||
}
|
||||
|
||||
update(
|
||||
data: UserTypes.UpdateUserDTO[],
|
||||
sharedContext?: Context
|
||||
): Promise<UserTypes.UserDTO[]>
|
||||
update(
|
||||
data: UserTypes.UpdateUserDTO,
|
||||
sharedContext?: Context
|
||||
): Promise<UserTypes.UserDTO>
|
||||
|
||||
@InjectManager("baseRepository_")
|
||||
@EmitEvents()
|
||||
async update(
|
||||
data: UserTypes.UpdateUserDTO | UserTypes.UpdateUserDTO[],
|
||||
@MedusaContext() sharedContext: Context = {}
|
||||
): Promise<UserTypes.UserDTO | UserTypes.UserDTO[]> {
|
||||
const input = Array.isArray(data) ? data : [data]
|
||||
|
||||
const updatedUsers = await this.userService_.update(input, sharedContext)
|
||||
|
||||
const serializedUsers = await this.baseRepository_.serialize<
|
||||
UserTypes.UserDTO[]
|
||||
>(updatedUsers, {
|
||||
populate: true,
|
||||
})
|
||||
|
||||
sharedContext.messageAggregator?.saveRawMessageData(
|
||||
updatedUsers.map((user) => ({
|
||||
eventName: UserEvents.updated,
|
||||
metadata: {
|
||||
service: this.constructor.name,
|
||||
action: CommonEvents.UPDATED,
|
||||
object: "user",
|
||||
},
|
||||
data: { id: user.id },
|
||||
}))
|
||||
)
|
||||
|
||||
return Array.isArray(data) ? serializedUsers : serializedUsers[0]
|
||||
}
|
||||
|
||||
createInvites(
|
||||
data: UserTypes.CreateInviteDTO[],
|
||||
sharedContext?: Context
|
||||
): Promise<UserTypes.InviteDTO[]>
|
||||
createInvites(
|
||||
data: UserTypes.CreateInviteDTO,
|
||||
sharedContext?: Context
|
||||
): Promise<UserTypes.InviteDTO>
|
||||
|
||||
@InjectManager("baseRepository_")
|
||||
@EmitEvents()
|
||||
async createInvites(
|
||||
data: UserTypes.CreateInviteDTO[] | UserTypes.CreateInviteDTO,
|
||||
@MedusaContext() sharedContext: Context = {}
|
||||
): Promise<UserTypes.InviteDTO | UserTypes.InviteDTO[]> {
|
||||
const input = Array.isArray(data) ? data : [data]
|
||||
|
||||
const invites = await this.createInvites_(input, sharedContext)
|
||||
|
||||
const serializedInvites = await this.baseRepository_.serialize<
|
||||
UserTypes.InviteDTO[] | UserTypes.InviteDTO
|
||||
>(invites, {
|
||||
populate: true,
|
||||
})
|
||||
|
||||
sharedContext.messageAggregator?.saveRawMessageData(
|
||||
invites.map((invite) => ({
|
||||
eventName: UserEvents.invite_created,
|
||||
metadata: {
|
||||
service: this.constructor.name,
|
||||
action: CommonEvents.CREATED,
|
||||
object: "invite",
|
||||
},
|
||||
data: { id: invite.id },
|
||||
}))
|
||||
)
|
||||
|
||||
sharedContext.messageAggregator?.saveRawMessageData(
|
||||
invites.map((invite) => ({
|
||||
eventName: UserEvents.invite_token_generated,
|
||||
metadata: {
|
||||
service: this.constructor.name,
|
||||
action: "token_generated",
|
||||
object: "invite",
|
||||
},
|
||||
data: { id: invite.id },
|
||||
}))
|
||||
)
|
||||
|
||||
return Array.isArray(data) ? serializedInvites : serializedInvites[0]
|
||||
}
|
||||
|
||||
@InjectTransactionManager("baseRepository_")
|
||||
private async createInvites_(
|
||||
data: UserTypes.CreateInviteDTO[],
|
||||
@MedusaContext() sharedContext: Context = {}
|
||||
): Promise<TInvite[]> {
|
||||
const toCreate = data.map((invite) => {
|
||||
return {
|
||||
...invite,
|
||||
expires_at: new Date(),
|
||||
token: "placeholder",
|
||||
}
|
||||
})
|
||||
|
||||
return await this.inviteService_.create(toCreate, sharedContext)
|
||||
}
|
||||
|
||||
updateInvites(
|
||||
data: UserTypes.UpdateInviteDTO[],
|
||||
sharedContext?: Context
|
||||
): Promise<UserTypes.InviteDTO[]>
|
||||
updateInvites(
|
||||
data: UserTypes.UpdateInviteDTO,
|
||||
sharedContext?: Context
|
||||
): Promise<UserTypes.InviteDTO>
|
||||
|
||||
@InjectManager("baseRepository_")
|
||||
@EmitEvents()
|
||||
async updateInvites(
|
||||
data: UserTypes.UpdateInviteDTO | UserTypes.UpdateInviteDTO[],
|
||||
@MedusaContext() sharedContext: Context = {}
|
||||
): Promise<UserTypes.InviteDTO | UserTypes.InviteDTO[]> {
|
||||
const input = Array.isArray(data) ? data : [data]
|
||||
|
||||
const updatedInvites = await this.inviteService_.update(
|
||||
input,
|
||||
sharedContext
|
||||
)
|
||||
|
||||
const serializedInvites = await this.baseRepository_.serialize<
|
||||
UserTypes.InviteDTO[]
|
||||
>(updatedInvites, {
|
||||
populate: true,
|
||||
})
|
||||
|
||||
sharedContext.messageAggregator?.saveRawMessageData(
|
||||
serializedInvites.map((invite) => ({
|
||||
eventName: UserEvents.invite_updated,
|
||||
metadata: {
|
||||
service: this.constructor.name,
|
||||
action: CommonEvents.UPDATED,
|
||||
object: "invite",
|
||||
},
|
||||
data: { id: invite.id },
|
||||
}))
|
||||
)
|
||||
|
||||
return Array.isArray(data) ? serializedInvites : serializedInvites[0]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { Logger } from "@medusajs/types"
|
||||
|
||||
export type InitializeModuleInjectableDependencies = {
|
||||
logger?: Logger
|
||||
}
|
||||
|
||||
export * from "./services"
|
||||
@@ -0,0 +1 @@
|
||||
export * as InviteServiceTypes from "./invite"
|
||||
@@ -0,0 +1,5 @@
|
||||
export interface CreateInviteDTO {
|
||||
email: string
|
||||
accepted?: boolean
|
||||
metadata?: Record<string, unknown> | null
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"lib": [
|
||||
"es2020"
|
||||
],
|
||||
"target": "es2020",
|
||||
"outDir": "./dist",
|
||||
"esModuleInterop": true,
|
||||
"declaration": true,
|
||||
"module": "commonjs",
|
||||
"moduleResolution": "node",
|
||||
"emitDecoratorMetadata": true,
|
||||
"experimentalDecorators": true,
|
||||
"sourceMap": false,
|
||||
"noImplicitReturns": true,
|
||||
"strictNullChecks": true,
|
||||
"strictFunctionTypes": true,
|
||||
"noImplicitThis": true,
|
||||
"allowJs": true,
|
||||
"skipLibCheck": true,
|
||||
"downlevelIteration": true,
|
||||
// to use ES5 specific tooling
|
||||
"baseUrl": ".",
|
||||
"resolveJsonModule": true,
|
||||
"paths": {
|
||||
"@models": [
|
||||
"./src/models"
|
||||
],
|
||||
"@services": [
|
||||
"./src/services"
|
||||
],
|
||||
"@repositories": [
|
||||
"./src/repositories"
|
||||
],
|
||||
"@types": [
|
||||
"./src/types"
|
||||
]
|
||||
}
|
||||
},
|
||||
"include": [
|
||||
"src"
|
||||
],
|
||||
"exclude": [
|
||||
"dist",
|
||||
"./src/**/__tests__",
|
||||
"./src/**/__mocks__",
|
||||
"./src/**/__fixtures__",
|
||||
"node_modules"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"extends": "./tsconfig.json",
|
||||
"include": ["src", "integration-tests"],
|
||||
"exclude": ["node_modules", "dist"],
|
||||
"compilerOptions": {
|
||||
"sourceMap": true
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user