0
# Base Service
1
2
Core service functionality providing transaction management, query building, validation utilities, and decorator pattern support. All other service interfaces in medusa-interfaces extend this base class.
3
4
**Deprecation Notice**: Use `TransactionBaseService` from @medusajs/medusa instead.
5
6
## Capabilities
7
8
### Constructor
9
10
Creates a new BaseService instance with an empty decorators array.
11
12
```javascript { .api }
13
/**
14
* Creates a new BaseService instance
15
*/
16
constructor();
17
```
18
19
### Transaction Management
20
21
Methods for managing database transactions and ensuring data consistency.
22
23
```javascript { .api }
24
/**
25
* Returns this instance - warns about missing custom implementation
26
* @returns {BaseService} this instance
27
*/
28
withTransaction(): BaseService;
29
30
/**
31
* Wraps work within a transactional block with optional isolation level and error handling
32
* @param {function} work - The transactional work to be done
33
* @param {string|function} isolationOrErrorHandler - Isolation level or error handler function
34
* @param {function|boolean} maybeErrorHandlerOrDontFail - Error handler or don't fail flag
35
* @returns {Promise<any>} Result of the transactional work
36
*/
37
atomicPhase_(
38
work: function,
39
isolationOrErrorHandler?: string | function,
40
maybeErrorHandlerOrDontFail?: function | boolean
41
): Promise<any>;
42
43
/**
44
* Determines if a transaction should be retried based on error code
45
* @param {object} err - Error object to check
46
* @returns {boolean} True if transaction should be retried
47
*/
48
shouldRetryTransaction(err: object): boolean;
49
```
50
51
**Usage Example:**
52
53
```javascript
54
import { BaseService } from "medusa-interfaces";
55
56
class MyService extends BaseService {
57
async performWork() {
58
return await this.atomicPhase_(async (manager) => {
59
// Database operations within transaction
60
const result = await manager.save(entity);
61
return result;
62
});
63
}
64
}
65
```
66
67
### Query Building
68
69
Utility for building TypeORM queries with selectors and configuration.
70
71
```javascript { .api }
72
/**
73
* Used to build TypeORM queries
74
* @param {object} selector - Query selector object
75
* @param {object} config - Query configuration options
76
* @returns {object} Built query object
77
*/
78
buildQuery_(selector: object, config?: object): object;
79
```
80
81
### Validation
82
83
ID validation with optional configuration for prefix and length checking.
84
85
```javascript { .api }
86
/**
87
* Confirms whether a given raw id is valid
88
* @param {string} rawId - The id to validate
89
* @param {object} config - Optional config for prefix and length validation
90
* @returns {string} The validated rawId
91
* @throws {Error} If rawId is null or undefined
92
*/
93
validateId_(rawId: string, config?: object): string;
94
```
95
96
### Metadata Management
97
98
Method for setting metadata on entities.
99
100
```javascript { .api }
101
/**
102
* Dedicated method to set metadata on an entity
103
* @param {object} obj - The entity to apply metadata to
104
* @param {object} metadata - The metadata to set
105
* @returns {Promise<object>} Promise resolving to the updated result
106
*/
107
setMetadata_(obj: object, metadata: object): Promise<object>;
108
```
109
110
### Decorator Pattern
111
112
Support for adding and running decorators to extend service functionality.
113
114
```javascript { .api }
115
/**
116
* Adds a decorator to a service - must be a function
117
* @param {function} fn - The decorator function to add
118
* @throws {Error} If fn is not a function
119
*/
120
addDecorator(fn: function): void;
121
122
/**
123
* Runs all registered decorators on an object in registration order
124
* @param {object} obj - The object to decorate
125
* @param {array} fields - Fields array for decoration
126
* @param {array} expandFields - Expand fields array for decoration
127
* @returns {Promise<object>} The decorated object
128
*/
129
runDecorators_(obj: object, fields?: array, expandFields?: array): Promise<object>;
130
```
131
132
**Usage Example:**
133
134
```javascript
135
import { BaseService } from "medusa-interfaces";
136
137
class MyService extends BaseService {
138
constructor() {
139
super();
140
141
// Add a decorator that adds timestamps
142
this.addDecorator((obj) => ({
143
...obj,
144
decorated_at: new Date().toISOString()
145
}));
146
}
147
148
async processObject(obj) {
149
// Run decorators on the object
150
return await this.runDecorators_(obj);
151
}
152
}
153
```
154
155
## Properties
156
157
### Instance Properties
158
159
```javascript { .api }
160
/**
161
* Array of decorator functions registered with addDecorator
162
*/
163
decorators_: function[];
164
165
/**
166
* Current transaction manager instance
167
*/
168
manager_: object;
169
170
/**
171
* Current transaction manager for atomic operations
172
*/
173
transactionManager_: object;
174
```
175
176
## Dependencies
177
178
BaseService imports utilities from @medusajs/medusa:
179
180
- `buildQuery` - For building TypeORM queries
181
- `setMetadata` - For setting entity metadata
182
- `validateId` - For ID validation