0
# LoopBack Core
1
2
LoopBack Core (`@loopback/core`) is the foundational framework for building LoopBack 4 applications. It provides the core constructs including Application containers, Component systems, Server abstractions, and lifecycle management. The package includes a complete dependency injection system re-exported from `@loopback/context`, enabling fast, scalable, and extensible Node.js applications and microservices.
3
4
## Package Information
5
6
- **Package Name**: @loopback/core
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install @loopback/core`
10
11
## Core Imports
12
13
```typescript
14
import { Application, Component, Server } from "@loopback/core";
15
```
16
17
For specific functionality:
18
19
```typescript
20
import {
21
Application,
22
Component,
23
lifeCycleObserver,
24
service,
25
extensionPoint,
26
extensions
27
} from "@loopback/core";
28
```
29
30
CommonJS:
31
32
```javascript
33
const { Application, Component, Server } = require("@loopback/core");
34
```
35
36
## Basic Usage
37
38
```typescript
39
import { Application, Component } from "@loopback/core";
40
41
// Create an application
42
const app = new Application({
43
name: 'my-app',
44
shutdown: {
45
signals: ['SIGTERM'],
46
gracePeriod: 5000
47
}
48
});
49
50
// Register a component
51
class MyComponent implements Component {
52
controllers = [MyController];
53
providers = {
54
'services.logger': LoggerProvider
55
};
56
}
57
58
app.component(MyComponent);
59
60
// Start the application
61
await app.start();
62
console.log('Application is running');
63
64
// Graceful shutdown
65
process.on('SIGTERM', async () => {
66
await app.stop();
67
});
68
```
69
70
## Architecture
71
72
LoopBack Core is built around several key architectural patterns:
73
74
- **Application Container**: Central IoC container managing all application components, servers, and services
75
- **Component System**: Modular architecture where functionality is packaged into reusable components
76
- **Lifecycle Management**: Coordinated initialization, start, and stop sequences across all registered observers
77
- **Dependency Injection**: Complete IoC system with constructor, property, and method injection
78
- **Extension Points**: Plugin architecture enabling applications to be extended with custom functionality
79
- **Server Abstraction**: Generic server lifecycle management decoupled from specific server implementations
80
- **Context Hierarchy**: Hierarchical dependency injection contexts enabling proper scoping and isolation
81
82
## Capabilities
83
84
### Application Container
85
86
Core application class that serves as the main container for components, servers, controllers, and services. Extends Context to provide dependency injection throughout the application.
87
88
```typescript { .api }
89
class Application extends Context implements LifeCycleObserver {
90
constructor(config?: ApplicationConfig, parent?: Context);
91
constructor(parent: Context);
92
93
// Component registration
94
component<T extends Component = Component>(
95
componentCtor: Constructor<T>,
96
nameOrOptions?: string | BindingFromClassOptions
97
): Binding<T>;
98
99
// Server management
100
server<T extends Server>(
101
ctor: Constructor<T>,
102
nameOrOptions?: string | BindingFromClassOptions
103
): Binding<T>;
104
105
getServer<T extends Server>(target: Constructor<T> | string): Promise<T>;
106
107
// Controller registration
108
controller<T>(
109
controllerCtor: ControllerClass<T>,
110
nameOrOptions?: string | BindingFromClassOptions
111
): Binding<T>;
112
113
// Service registration
114
service<S>(
115
cls: ServiceOrProviderClass<S>,
116
nameOrOptions?: string | ServiceOptions
117
): Binding<S>;
118
119
// Lifecycle management
120
init(): Promise<void>;
121
start(): Promise<void>;
122
stop(): Promise<void>;
123
124
readonly state: string;
125
}
126
127
interface ApplicationConfig {
128
name?: string;
129
shutdown?: ShutdownOptions;
130
[prop: string]: any;
131
}
132
```
133
134
[Application Container](./application.md)
135
136
### Component System
137
138
Modular architecture for packaging and contributing functionality to applications. Components can declare controllers, providers, servers, and other resources.
139
140
```typescript { .api }
141
interface Component {
142
controllers?: ControllerClass[];
143
providers?: ProviderMap;
144
classes?: ClassMap;
145
servers?: { [name: string]: Constructor<Server> };
146
lifeCycleObservers?: Constructor<LifeCycleObserver>[];
147
services?: ServiceOrProviderClass[];
148
bindings?: Binding[];
149
components?: Constructor<Component>[];
150
}
151
152
function mountComponent(app: Application, component: Component): void;
153
```
154
155
[Component System](./components.md)
156
157
### Lifecycle Management
158
159
Coordinated lifecycle management for application startup and shutdown sequences. Provides hooks for initialization, start, and stop phases.
160
161
```typescript { .api }
162
interface LifeCycleObserver {
163
init?(...injectedArgs: unknown[]): ValueOrPromise<void>;
164
start?(...injectedArgs: unknown[]): ValueOrPromise<void>;
165
stop?(...injectedArgs: unknown[]): ValueOrPromise<void>;
166
}
167
168
function lifeCycleObserver(group?: string, ...specs: BindingSpec[]): ClassDecorator;
169
170
class LifeCycleObserverRegistry implements LifeCycleObserver {
171
getObserverGroupsByOrder(): LifeCycleObserverGroup[];
172
init(): Promise<void>;
173
start(): Promise<void>;
174
stop(): Promise<void>;
175
}
176
```
177
178
[Lifecycle Management](./lifecycle.md)
179
180
### Service Layer
181
182
Service discovery and dependency injection system for registering and consuming services throughout the application.
183
184
```typescript { .api }
185
function service(
186
serviceInterface?: ServiceInterface,
187
metadata?: InjectionMetadata
188
): PropertyDecorator & ParameterDecorator;
189
190
function createServiceBinding<S>(
191
cls: ServiceOrProviderClass<S>,
192
options?: ServiceOptions
193
): Binding<S>;
194
195
type ServiceInterface = string | symbol | Function;
196
```
197
198
[Service Layer](./services.md)
199
200
### Extension Points
201
202
Plugin architecture enabling applications to define extension points and register extensions dynamically.
203
204
```typescript { .api }
205
function extensionPoint(name: string, ...specs: BindingSpec[]): ClassDecorator;
206
207
function extensions(
208
extensionPointName?: string,
209
metadata?: InjectionMetadata
210
): PropertyDecorator & ParameterDecorator;
211
212
function addExtension(
213
context: Context,
214
extensionPointName: string,
215
extensionClass: Constructor<unknown>,
216
options?: BindingFromClassOptions
217
): Binding<unknown>;
218
```
219
220
[Extension Points](./extensions.md)
221
222
### Context & Dependency Injection
223
224
Complete IoC container system with hierarchical contexts, binding management, and type-safe dependency injection.
225
226
```typescript { .api }
227
class Context {
228
bind<ValueType = BoundValue>(key: BindingAddress<ValueType>): Binding<ValueType>;
229
get<ValueType>(keyWithPath: BindingAddress<ValueType>): Promise<ValueType>;
230
getSync<ValueType>(keyWithPath: BindingAddress<ValueType>): ValueType;
231
}
232
233
function inject(
234
bindingSelector?: BindingSelector<unknown>,
235
metadata?: InjectionMetadata
236
): PropertyDecorator & ParameterDecorator;
237
238
function injectable<T>(
239
...specs: BindingSpec[]
240
): ClassDecorator;
241
```
242
243
[Context & Dependency Injection](./context-api.md)
244
245
## Types
246
247
Core type definitions used throughout the LoopBack Core system:
248
249
```typescript { .api }
250
// Application types
251
interface ApplicationMetadata extends JSONObject {
252
name: string;
253
version: string;
254
description: string;
255
}
256
257
interface ShutdownOptions {
258
signals?: NodeJS.Signals[];
259
gracePeriod?: number;
260
}
261
262
// Component types
263
interface ProviderMap {
264
[key: string]: Constructor<Provider<BoundValue>>;
265
}
266
267
interface ClassMap {
268
[key: string]: Constructor<BoundValue>;
269
}
270
271
// Server types
272
interface Server extends LifeCycleObserver {
273
readonly listening: boolean;
274
}
275
276
// Controller and service types
277
type ControllerClass<T = any> = Constructor<T>;
278
type ServiceOrProviderClass<T = any> =
279
| Constructor<T | Provider<T>>
280
| DynamicValueProviderClass<T>;
281
282
// Mixin utility
283
type MixinTarget<T extends object> = Constructor<{
284
[P in keyof T]: T[P];
285
}>;
286
287
// Lifecycle types
288
interface LifeCycleObserverGroup {
289
group: string;
290
bindings: Readonly<Binding<LifeCycleObserver>>[];
291
}
292
293
interface LifeCycleObserverOptions {
294
orderedGroups: string[];
295
disabledGroups?: string[];
296
parallel?: boolean;
297
}
298
299
// Core binding keys and tags
300
namespace CoreBindings {
301
const APPLICATION_INSTANCE: BindingKey<Application>;
302
const APPLICATION_CONFIG: BindingKey<ApplicationConfig>;
303
const APPLICATION_METADATA: BindingKey<ApplicationMetadata>;
304
const SERVERS: string;
305
const COMPONENTS: string;
306
const CONTROLLERS: string;
307
const CONTROLLER_CLASS: BindingKey<ControllerClass>;
308
const CONTROLLER_METHOD_NAME: BindingKey<string>;
309
const CONTROLLER_METHOD_META: string;
310
const CONTROLLER_CURRENT: BindingKey<any>;
311
const LIFE_CYCLE_OBSERVERS: string;
312
const LIFE_CYCLE_OBSERVER_REGISTRY: BindingKey<LifeCycleObserverRegistry>;
313
const LIFE_CYCLE_OBSERVER_OPTIONS: BindingKey<LifeCycleObserverOptions>;
314
}
315
316
namespace CoreTags {
317
const COMPONENT: string;
318
const SERVER: string;
319
const CONTROLLER: string;
320
const SERVICE: string;
321
const SERVICE_INTERFACE: string;
322
const LIFE_CYCLE_OBSERVER: string;
323
const LIFE_CYCLE_OBSERVER_GROUP: string;
324
const EXTENSION_FOR: string;
325
const EXTENSION_POINT: string;
326
}
327
```