1 import { Tabs, TabsContent, TabsContentWrapper, TabsList, TabsTriggerVertical } from "docs-ui"
2
3 export const metadata = {
4 title: `${pageNumber} Service Factory`,
5 }
6
7 # {metadata.title}
8
9 In this chapter, you’ll learn about what the service factory is and how to use it.
10
11 ## What is the Service Factory?
12
13 Medusa provides a service factory that your module’s main service can extend.
14
15 The service factory generates data management methods for your data models, saving you time on implementing these methods manually.
16
17 <Note title="Extend the service factory when" type="success">
18
19 Your service provides data-management functionality for your data models.
20
21 </Note>
22
23 ---
24
25 ## How to Extend the Service Factory?
26
27 Medusa provides the service factory as a `MedusaService` function your service extends. The function creates and returns a service class with generated data-management methods.
28
29 For example, create the file `src/modules/blog/service.ts` with the following content:
30
31 export const highlights = [
32 ["4", "MedusaService", "The service factory function."],
33 ["5", "Post", "The data model to generate data-management methods for."]
34 ]
35
36 ```ts title="src/modules/blog/service.ts" highlights={highlights}
37 import { MedusaService } from "@medusajs/framework/utils"
38 import Post from "./models/post"
39
40 class BlogModuleService extends MedusaService({
41 Post,
42 }){
43 // TODO implement custom methods
44 }
45
46 export default BlogModuleService
47 ```
48
49 ### MedusaService Parameters
50
51 The `MedusaService` function accepts one parameter, which is an object of data models for which to generate data-management methods.
52
53 In the example above, since the `BlogModuleService` extends `MedusaService`, it has methods to manage the `Post` data model, such as `createPosts`.
54
55 ### Generated Methods
56
57 The service factory generates methods to manage the records of each of the data models provided in the first parameter in the database.
58
59 The method names are the operation name, suffixed by the data model's key in the object parameter passed to `MedusaService`.
60
61 For example, the following methods are generated for the service above:
62
63 <Note>
64
65 Find a complete reference of each of the methods in [this documentation](!resources!/service-factory-reference)
66
67 </Note>
68
69 <Tabs defaultValue="listPosts" layoutType="vertical" className="mt-2">
70 <TabsList>
71 <TabsTriggerVertical value="listPosts">listPosts</TabsTriggerVertical>
72 <TabsTriggerVertical value="listAndCountPosts">listAndCountPosts</TabsTriggerVertical>
73 <TabsTriggerVertical value="retrievePost">retrievePost</TabsTriggerVertical>
74 <TabsTriggerVertical value="createPosts">createPosts</TabsTriggerVertical>
75 <TabsTriggerVertical value="updatePosts">updatePosts</TabsTriggerVertical>
76 <TabsTriggerVertical value="deletePosts">deletePosts</TabsTriggerVertical>
77 <TabsTriggerVertical value="softDeletePosts">softDeletePosts</TabsTriggerVertical>
78 <TabsTriggerVertical value="restorePosts">restorePosts</TabsTriggerVertical>
79 </TabsList>
80 <TabsContentWrapper className="[&_h3]:!mt-0">
81 <TabsContent value="listPosts">
82
83 ### listPosts
84
85 This method retrieves an array of records based on filters and pagination configurations.
86
87 For example:
88
89 ```ts
90 const posts = await blogModuleService
91 .listPosts()
92
93 // with filters
94 const posts = await blogModuleService
95 .listPosts({
96 id: ["123"]
97 })
98 ```
99
100 </TabsContent>
101 <TabsContent value="listAndCountPosts">
102
103 ### listAndCountPosts
104
105 This method retrieves a tuple of an array of records and the total count of available records based on the filters and pagination configurations provided.
106
107 For example:
108
109 ```ts
110 const [
111 posts,
112 count
113 ] = await blogModuleService.listAndCountPosts()
114
115 // with filters
116 const [
117 posts,
118 count
119 ] = await blogModuleService.listAndCountPosts({
120 id: ["123"]
121 })
122 ```
123
124 </TabsContent>
125 <TabsContent value="retrievePost">
126
127 ### retrievePost
128
129 This method retrieves a record by its ID.
130
131 For example:
132
133 ```ts
134 const post = await blogModuleService
135 .retrievePost("123")
136 ```
137
138 </TabsContent>
139 <TabsContent value="createPosts">
140
141 ### createPosts
142
143 This method creates and retrieves records of the data model.
144
145 For example:
146
147 ```ts
148 const post = await blogModuleService
149 .createPosts({
150 title: "test"
151 })
152
153 // create multiple
154 const posts = await blogModuleService
155 .createPosts([
156 {
157 title: "test"
158 },
159 {
160 title: "test 2"
161 },
162 ])
163 ```
164
165 </TabsContent>
166 <TabsContent value="updatePosts">
167
168 ### updatePosts
169
170 This method updates and retrieves records of the data model.
171
172 For example:
173
174 ```ts
175 const post = await blogModuleService
176 .updatePosts({
177 id: "123",
178 title: "test"
179 })
180
181 // update multiple
182 const posts = await blogModuleService
183 .updatePosts([
184 {
185 id: "123",
186 title: "test"
187 },
188 {
189 id: "321",
190 title: "test 2"
191 },
192 ])
193
194 // use filters
195 const posts = await blogModuleService
196 .updatePosts([
197 {
198 selector: {
199 id: ["123", "321"]
200 },
201 data: {
202 title: "test"
203 }
204 },
205 ])
206 ```
207
208 </TabsContent>
209 <TabsContent value="deletePosts">
210
211 ### deletePosts
212
213 This method deletes records by an ID or filter.
214
215 For example:
216
217 ```ts
218 await blogModuleService.deletePosts("123")
219
220 // delete multiple
221 await blogModuleService.deletePosts([
222 "123", "321"
223 ])
224
225 // use filters
226 await blogModuleService.deletePosts({
227 selector: {
228 id: ["123", "321"]
229 }
230 })
231 ```
232
233 </TabsContent>
234 <TabsContent value="softDeletePosts">
235
236 ### softDeletePosts
237
238 This method soft-deletes records using an array of IDs or an object of filters.
239
240 For example:
241
242 ```ts
243 await blogModuleService.softDeletePosts("123")
244
245 // soft-delete multiple
246 await blogModuleService.softDeletePosts([
247 "123", "321"
248 ])
249
250 // use filters
251 await blogModuleService.softDeletePosts({
252 id: ["123", "321"]
253 })
254 ```
255
256 </TabsContent>
257 <TabsContent value="restorePosts">
258
259 ### restorePosts
260
261 This method restores soft-deleted records using an array of IDs or an object of filters.
262
263 For example:
264
265 ```ts
266 await blogModuleService.restorePosts([
267 "123", "321"
268 ])
269
270 // use filters
271 await blogModuleService.restorePosts({
272 id: ["123", "321"]
273 })
274 ```
275
276 </TabsContent>
277 </TabsContentWrapper>
278 </Tabs>
279
280 ### Using a Constructor
281
282 If you implement a `constructor` in your service, make sure to call `super` and pass it `...arguments`.
283
284 For example:
285
286 ```ts highlights={[["8"]]}
287 import { MedusaService } from "@medusajs/framework/utils"
288 import Post from "./models/post"
289
290 class BlogModuleService extends MedusaService({
291 Post,
292 }){
293 constructor() {
294 super(...arguments)
295 }
296 }
297
298 export default BlogModuleService
299 ```
300
301 ---
302
303 ## Generated Internal Services
304
305 The service factory also generates internal services for each data model passed to the `MedusaService` function. These services are registered in the module's container and can be resolved using their camel-cased names.
306
307 For example, if the `BlogModuleService` is defined as follows:
308
309 ```ts
310 import { MedusaService } from "@medusajs/framework/utils"
311 import Post from "./models/post"
312
313 class BlogModuleService extends MedusaService({
314 Post,
315 }){
316 }
317
318 export default BlogModuleService
319 ```
320
321 Then, you'll have a `postService` registered in the module's container that allows you to manage posts.
322
323 Generated internal services have the same methods as the `BlogModuleService`, such as `create`, `retrieve`, `update`, and `delete`, but without the data model name suffix.
324
325 These services are useful when you need to perform database operations in loaders, as they are executed before the module's services are registered. Learn more in the [Module Container](../container/page.mdx) documentation.
326
327 For example, you can create a loader that logs the number of posts in the database:
328
329 ```ts
330 import { LoaderOptions } from "@medusajs/framework/types"
331
332 export default async function helloWorldLoader({
333 container,
334 }: LoaderOptions) {
335 const postService = container.resolve("postService")
336
337 const [_, count] = await postService.listAndCount()
338
339 console.log(`[helloWorldLoader]: There are ${count} posts in the database.`)
340 }
341 ```