Skip to content

Commit adba017

Browse files
committedJun 24, 2019
Completed User Endpoint Setup
1 parent f2ae4a2 commit adba017

File tree

10 files changed

+79
-44
lines changed

10 files changed

+79
-44
lines changed
 

‎ormconfig.json

-7
This file was deleted.

‎package-lock.json

+19
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎package.json

+2
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
},
3131
"homepage": "https://github.com/ioedeveloper/Shadow-Backend#readme",
3232
"dependencies": {
33+
"body-parser": "^1.19.0",
3334
"chai": "^4.2.0",
3435
"express": "^4.17.1",
3536
"mocha": "^6.1.4",
@@ -42,6 +43,7 @@
4243
"@types/chai": "^4.1.7",
4344
"@types/express": "^4.17.0",
4445
"@types/mocha": "^5.2.7",
46+
"@types/mongodb": "^3.1.28",
4547
"@types/node": "^12.0.7",
4648
"nodemon": "^1.19.1",
4749
"tslint": "^5.17.0"

‎src/api/user.ts

+2
Original file line numberDiff line numberDiff line change
@@ -22,3 +22,5 @@ router.post('/signup', async function(req: Request, res: Response) {
2222
}
2323

2424
});
25+
26+
export { router };

‎src/config/types/user.ts

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1+
import { ObjectID } from 'typeorm';
12
interface IUser {
2-
id: number;
3+
_id: ObjectID;
34
email: string;
45
extensionId: string;
56
deleted: boolean;

‎src/model/user.ts

+6-6
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,16 @@
1-
import { Entity, PrimaryGeneratedColumn, Column } from 'typeorm';
1+
import { Entity, ObjectID, ObjectIdColumn, Column } from 'typeorm';
22

33
@Entity()
44
export class UserModel {
5-
@PrimaryGeneratedColumn
6-
id: number;
5+
@ObjectIdColumn()
6+
_id: ObjectID
77

8-
@Column
8+
@Column()
99
email: string;
1010

11-
@Column
11+
@Column()
1212
extensionId: string;
1313

14-
@Column
14+
@Column()
1515
deleted: boolean = false;
1616
}

‎src/server.ts

+31-20
Original file line numberDiff line numberDiff line change
@@ -2,31 +2,42 @@
22
import { Request, Response } from 'express';
33
import express = require('express');
44
import {createConnection} from 'typeorm';
5+
import bodyParser = require('body-parser');
6+
import * as UserEndpoint from './api/user';
57

68
// establish database connection.
7-
createConnection().then(() => {
8-
// tslint:disable-next-line:no-console
9-
console.log('Database Connection Established...');
9+
(async () => {
10+
try {
11+
const connection = await createConnection();
12+
// tslint:disable-next-line:no-console
13+
console.log('Database Connection Established...');
1014

11-
// create a new express application instance
12-
const app: express.Application = express();
15+
// create a new express application instance
16+
const app: express.Application = express();
1317

1418
// the port the express app will listen on
15-
const port: any = process.env.PORT || 2002;
19+
const port: any = process.env.PORT || 2002;
1620

17-
app.get('/', (req: Request, res: Response) => {
18-
res.setHeader('Content-Type', 'application/json');
19-
res.send(JSON.stringify({
20-
status: 200,
21-
message: 'Service is up!',
22-
}));
23-
});
21+
app.use(bodyParser.json());
22+
app.use(bodyParser.urlencoded({ extended: false }));
2423

25-
// serve the application at the given port
26-
app.listen(port, () => {
27-
// tslint:disable-next-line:no-console
28-
console.log(`Listening at http://localhost:${port}/`);
29-
});
24+
app.use('/user', UserEndpoint.router);
3025

31-
// tslint:disable-next-line:no-console
32-
}).catch((error) => console.log(`Error: ${error}`));
26+
app.get('/', (req: Request, res: Response) => {
27+
res.setHeader('Content-Type', 'application/json');
28+
res.send(JSON.stringify({
29+
status: 200,
30+
message: 'Service is up!',
31+
}));
32+
});
33+
34+
// serve the application at the given port
35+
app.listen(port, () => {
36+
// tslint:disable-next-line:no-console
37+
console.log(`Listening at http://localhost:${port}/`);
38+
});
39+
} catch (error) {
40+
// tslint:disable-next-line:no-console
41+
console.log(`Error: ${error}`);
42+
}
43+
})();

‎src/service/userDataService.ts

+14-8
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,15 @@
1-
import { MongoRepository, getConnection, UpdateWriteOpResult } from 'typeorm';
1+
import { MongoRepository, getMongoRepository, UpdateWriteOpResult } from 'typeorm';
22
import { UserModel } from '../model/user';
33

44
export class UserDataService {
55
private _db: MongoRepository<UserModel>;
66

7-
constructor() {
8-
this._db = getConnection().getMongoRepository(UserModel);
9-
}
10-
117
public async create(newUser: UserModel): Promise<UserModel> {
128
const userModel: UserModel = new UserModel();
13-
userModel.id = newUser.id;
149
userModel.email = newUser.email;
1510
userModel.extensionId = newUser.extensionId;
1611
try {
12+
if (!this._db) await this._init();
1713
const user = await this._db.save(userModel);
1814
return user;
1915
} catch (error) {
@@ -26,6 +22,7 @@ export class UserDataService {
2622
if (!take) take = 10;
2723
query.deleted = false;
2824
try {
25+
if (!this._db) await this._init();
2926
const users: UserModel[] = await this._db.find({
3027
where: query,
3128
skip,
@@ -40,6 +37,7 @@ export class UserDataService {
4037
public async findOneBy(query: UserModel): Promise<UserModel | undefined> {
4138
query.deleted = false;
4239
try {
40+
if (!this._db) await this._init();
4341
const user: UserModel | undefined = await this._db.findOne(query);
4442
return user;
4543
} catch (error) {
@@ -48,8 +46,9 @@ export class UserDataService {
4846
}
4947

5048
public async update(user: UserModel): Promise<UserModel> {
51-
if (!user.id) {
49+
if (!user._id) {
5250
try {
51+
if (!this._db) await this._init();
5352
const newUser = this.create(user);
5453
return newUser;
5554
} catch (error) {
@@ -58,7 +57,8 @@ export class UserDataService {
5857
} else {
5958
user.deleted = false;
6059
try {
61-
await this._db.findOneAndUpdate({id: user.id}, {
60+
if (!this._db) await this._init();
61+
await this._db.findOneAndUpdate({id: user._id}, {
6262
$set: {
6363
email: user.email,
6464
extensionId: user.extensionId,
@@ -74,6 +74,7 @@ export class UserDataService {
7474
public async countBy(query: UserModel): Promise<number> {
7575
query.deleted = false;
7676
try {
77+
if (!this._db) await this._init();
7778
const count = await this._db.count(query);
7879
return count;
7980
} catch (error) {
@@ -84,6 +85,7 @@ export class UserDataService {
8485
public async deleteBy(query: UserModel, userId: number): Promise<UpdateWriteOpResult> {
8586
query.deleted = false;
8687
try {
88+
if (!this._db) await this._init();
8789
const result: UpdateWriteOpResult = await this._db.updateMany(query, {
8890
$set: {
8991
deleted: true,
@@ -95,4 +97,8 @@ export class UserDataService {
9597
throw error;
9698
}
9799
}
100+
101+
private async _init() {
102+
this._db = getMongoRepository(UserModel);
103+
}
98104
}

‎tsconfig.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@
2626
// "strictNullChecks": true, /* Enable strict null checks. */
2727
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
2828
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
29-
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
29+
"strictPropertyInitialization": false, /* Enable strict checking of property initialization in classes. */
3030
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
3131
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
3232

‎tslint.json

+2-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,8 @@
33
"linterOptions": {
44
"exclude": [
55
"build",
6-
"node_modules"
6+
"node_modules",
7+
"src/model/*.ts"
78
]
89
},
910
"rules": {

0 commit comments

Comments
 (0)
Please sign in to comment.