-
Notifications
You must be signed in to change notification settings - Fork 208
/
application.ts
173 lines (150 loc) · 5.61 KB
/
application.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
// Copyright IBM Corp. 2019,2020. All Rights Reserved.
// Node module: loopback4-example-shopping
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
import {AuthenticationComponent} from '@loopback/authentication';
import {
JWTAuthenticationComponent,
TokenServiceBindings,
} from '@loopback/authentication-jwt';
import {AuthorizationComponent} from '@loopback/authorization';
import {BootMixin} from '@loopback/boot';
import {
ApplicationConfig,
BindingKey,
createBindingFromClass,
} from '@loopback/core';
import {RepositoryMixin, SchemaMigrationOptions} from '@loopback/repository';
import {RestApplication} from '@loopback/rest';
import {
RestExplorerBindings,
RestExplorerComponent,
} from '@loopback/rest-explorer';
import {ServiceMixin} from '@loopback/service-proxy';
import crypto from 'crypto';
import fs from 'fs';
import path from 'path';
import {PasswordHasherBindings, UserServiceBindings} from './keys';
import {UserWithPassword} from './models';
import {
OrderRepository,
ProductRepository,
ShoppingCartRepository,
UserRepository,
} from './repositories';
import {ShoppySequence} from './sequence';
import {
UserManagementService,
BcryptHasher,
SecuritySpecEnhancer,
JWTService,
} from './services';
import YAML = require('yaml');
import {ErrorHandlerMiddlewareProvider} from './middlewares';
/**
* Information from package.json
*/
export interface PackageInfo {
name: string;
version: string;
description: string;
}
export const PackageKey = BindingKey.create<PackageInfo>('application.package');
const pkg: PackageInfo = require('../package.json');
export class ShoppingApplication extends BootMixin(
ServiceMixin(RepositoryMixin(RestApplication)),
) {
constructor(options?: ApplicationConfig) {
super(options);
// Bind authentication component related elements
this.component(AuthenticationComponent);
this.component(JWTAuthenticationComponent);
this.component(AuthorizationComponent);
this.setUpBindings();
// Set up the custom sequence
this.sequence(ShoppySequence);
// Set up default home page
this.static('/', path.join(__dirname, '../public'));
// Customize @loopback/rest-explorer configuration here
this.bind(RestExplorerBindings.CONFIG).to({
path: '/explorer',
});
this.component(RestExplorerComponent);
this.projectRoot = __dirname;
// Customize @loopback/boot Booter Conventions here
this.bootOptions = {
controllers: {
// Customize ControllerBooter Conventions here
dirs: ['controllers'],
extensions: ['.controller.js'],
nested: true,
},
};
}
setUpBindings(): void {
// Bind package.json to the application context
this.bind(PackageKey).to(pkg);
// Bind bcrypt hash services
this.bind(PasswordHasherBindings.ROUNDS).to(10);
this.bind(PasswordHasherBindings.PASSWORD_HASHER).toClass(BcryptHasher);
this.bind(TokenServiceBindings.TOKEN_SERVICE).toClass(JWTService);
this.bind(UserServiceBindings.USER_SERVICE).toClass(UserManagementService);
this.add(createBindingFromClass(SecuritySpecEnhancer));
this.add(createBindingFromClass(ErrorHandlerMiddlewareProvider));
// Use JWT secret from JWT_SECRET environment variable if set
// otherwise create a random string of 64 hex digits
const secret =
process.env.JWT_SECRET ?? crypto.randomBytes(32).toString('hex');
this.bind(TokenServiceBindings.TOKEN_SECRET).to(secret);
}
// Unfortunately, TypeScript does not allow overriding methods inherited
// from mapped types. https://github.com/microsoft/TypeScript/issues/38496
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
async start(): Promise<void> {
// Use `databaseSeeding` flag to control if products/users should be pre
// populated into the database. Its value is default to `true`.
if (this.options.databaseSeeding !== false) {
await this.migrateSchema();
}
return super.start();
}
async migrateSchema(options?: SchemaMigrationOptions): Promise<void> {
await super.migrateSchema(options);
// Pre-populate products
const productRepo = await this.getRepository(ProductRepository);
await productRepo.deleteAll();
const productsDir = path.join(__dirname, '../fixtures/products');
const productFiles = fs.readdirSync(productsDir);
for (const file of productFiles) {
if (file.endsWith('.yml')) {
const productFile = path.join(productsDir, file);
const yamlString = fs.readFileSync(productFile, 'utf8');
const product = YAML.parse(yamlString);
await productRepo.create(product);
}
}
// Pre-populate users
const userRepo = await this.getRepository(UserRepository);
await userRepo.deleteAll();
const usersDir = path.join(__dirname, '../fixtures/users');
const userFiles = fs.readdirSync(usersDir);
for (const file of userFiles) {
if (file.endsWith('.yml')) {
const userFile = path.join(usersDir, file);
const yamlString = YAML.parse(fs.readFileSync(userFile, 'utf8'));
const userWithPassword = new UserWithPassword(yamlString);
const userManagementService = await this.get<UserManagementService>(
UserServiceBindings.USER_SERVICE,
);
await userManagementService.createUser(userWithPassword);
}
}
// Delete existing shopping carts
const cartRepo = await this.getRepository(ShoppingCartRepository);
await cartRepo.deleteAll();
// Delete existing orders
const orderRepo = await this.getRepository(OrderRepository);
await orderRepo.deleteAll();
}
}