Skip to content

Commit 697fd64

Browse files
committed
user model created
1 parent 502365e commit 697fd64

4 files changed

Lines changed: 96 additions & 20 deletions

File tree

examples_new/microservices/auth/package-lock.json

Lines changed: 13 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

examples_new/microservices/auth/package.json

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,15 @@
1212
"license": "ISC",
1313
"dependencies": {
1414
"@chronosrx/common": "^1.0.1",
15+
"bcryptjs": "^2.4.3",
1516
"cookie-parser": "^1.4.6",
1617
"express": "^4.18.2",
1718
"jsonwebtoken": "^9.0.2",
1819
"mongoose": "^8.0.3",
1920
"ts-node-dev": "^2.0.0"
2021
},
2122
"devDependencies": {
23+
"@types/bcryptjs": "^2.4.6",
2224
"@types/cookie-parser": "^1.4.6",
2325
"@types/express": "^4.17.21",
2426
"@types/jest": "^29.5.11",

examples_new/microservices/auth/src/index.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,10 @@ import { app } from './app';
33
const PORT = process.env.PORT || 3000;
44

55
const start = async () => {
6+
if (!process.env.MONGO_URI) throw new Error('MONGO_URI must be defined')
7+
if (!process.env.JWT_SECRET) throw new Error('JWT_SECRET must be defined')
8+
if (!process.env.JWT_LIFETIME) throw new Error('JWT_LIFETIME must be defined')
9+
610
app.listen(PORT, () => {
711
console.log(`💥 App listening on ${PORT}`);
812
});
Lines changed: 77 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,25 +1,82 @@
1-
import { DbConnectionError, errorHandler } from '@chronosrx/common';
2-
const mongoose = require('mongoose');
3-
require('dotenv').config();
1+
import mongoose from 'mongoose';
2+
import bcrypt from 'bcryptjs';
3+
//define attrs
4+
interface UserAttrs {
5+
username: string;
6+
password: string;
7+
}
8+
// add a method 'build' to the UserModel
9+
// mongoose has built-in Model class that takes 'UserDoc'
10+
interface UserModel extends mongoose.Model<UserDoc> {
11+
build(attrs: UserAttrs): UserDoc;
12+
}
13+
//create user data in the database in this shape
14+
interface UserDoc extends mongoose.Document {
15+
username: string;
16+
password: string;
17+
}
18+
//create the Schema in mongoose with defined requirements
19+
const userSchema = new mongoose.Schema(
20+
{
21+
username: {
22+
type: String,
23+
required: true,
24+
unique: true,
25+
},
26+
password: {
27+
type: String,
28+
required: true,
29+
},
30+
},
31+
{
32+
//anytime we create Json formatted data, transform the user document as following
33+
toJSON: {
34+
transform(doc, ret) {
35+
ret.id = ret._id;
36+
delete ret._id;
37+
delete ret.password;
38+
delete ret.__v;
39+
},
40+
},
41+
}
42+
);
43+
//pre is built-in moogoose function that runs before the function 'save' takes place
44+
userSchema.pre('save', async function () {
45+
// Check if password has been created or modified
46+
if (!this.isModified('password')) return;
47+
//if the password is modified, hash the password
48+
const salt = await bcrypt.genSalt(10);
49+
const hashedPassword = await bcrypt.hash(this.password, salt);
50+
this.password = hashedPassword;
51+
});
52+
//schema has property: "method", custom define "comparePassword"
53+
userSchema.methods.comparePassword = async function (providedPassword: string) {
54+
const isMatch = await bcrypt.compare(providedPassword, this.password);
55+
return isMatch;
56+
};
457

5-
const MONGO_URI = process.env.MONGO_URI;
58+
userSchema.statics.build = (attrs: UserAttrs) => {
59+
//returning user document with (attrs) passed in
60+
return new User(attrs);
61+
};
662

7-
mongoose
8-
.connect(MONGO_URI, {
9-
useNewUrlParser: true,
10-
useUnifiedTopology: true,
11-
})
12-
.then(() => console.log(`Connected to MongoDB Database`))
13-
.catch(err => {
14-
throw new DbConnectionError();
15-
});
63+
const User = mongoose.model<UserDoc, UserModel>('User', userSchema);
1664

17-
const Schema = mongoose.Schema;
18-
const UserSchema = new Schema({
19-
username: { type: String, require: true },
20-
password: { type: String, require: true },
21-
});
65+
export { User };
66+
67+
// const newUser = User.create({
68+
// poo: 'doo',
69+
// doo: 'doo'
70+
// })
71+
72+
// const testUser = User.build({
73+
// username: 'derp',
74+
// password: 'derp',
75+
// doo: 'doo'
76+
// });
77+
// await testUser.save()
2278

23-
const User = mongoose.model('User', UserSchema);
79+
// const thisUser = await User.findById(userId)
80+
// res.send(thisUser) || res.json(thisUser)
2481

25-
module.exports = { User };
82+
// testUser.password = "derpdeedoo"

0 commit comments

Comments
 (0)