Commit c741d378 authored by “Yevgeniy's avatar “Yevgeniy

#8 added postgres sql connection code that wont work

parent bdf3f7b2
This diff is collapsed.
...@@ -29,6 +29,9 @@ ...@@ -29,6 +29,9 @@
"cors": "^2.8.5", "cors": "^2.8.5",
"express": "^4.18.2", "express": "^4.18.2",
"mongoose": "^6.7.0", "mongoose": "^6.7.0",
"nanoid": "^3.3.4" "nanoid": "^3.3.4",
"pg": "^8.8.0",
"reflect-metadata": "^0.1.13",
"typeorm": "^0.3.10"
} }
} }
import { DataSource } from "typeorm"
export const myDataSource = new DataSource({
type: "postgres",
host: "localhost",
port: 3308,
username: "test",
password: "test",
database: "planner",
entities: ["./models/*.ts"],
logging: true,
synchronize: true,
})
\ No newline at end of file
import { Schema, model } from 'mongoose'; import {
import bcrypt from 'bcrypt'; Column,
Entity,
PrimaryGeneratedColumn,
CreateDateColumn,
UpdateDateColumn,
BeforeInsert,
BeforeUpdate,
BaseEntity,
JoinColumn,
ManyToOne
} from 'typeorm';
import {nanoid} from 'nanoid'; import {nanoid} from 'nanoid';
import bcrypt from 'bcrypt';
const SALT_WORK_FACTOR= 10; const SALT_WORK_FACTOR= 10;
// 1. Create an interface representing a document in MongoDB. // enum UserRole {
// DIRECTOR = "director",
// WORKER = "worker",
// }
type UserRoleType = "worker" | "director";
interface IUser { interface IUser {
id:string;
name: string; name: string;
surname: string; surname: string;
email: string; email: string;
displayName: string; displayName: string;
password:string; password:string;
role: string; role: UserRoleType;
// createdAt: Date;
} }
// 2. Create a Schema corresponding to the document interface.
const UserSchema = new Schema<IUser>({
name: { type: String, required: true }, @Entity()
surname: { type: String, required: true }, export class User extends BaseEntity implements IUser {
email: { type: String, required: true }, @PrimaryGeneratedColumn('uuid')
displayName: { type: String, required: true }, id!: string
password: { type: String, required: true }, @Column({ name: 'first_name', type: 'varchar', length:20,nullable: false })
role:{type:String,default: 'user',enum:['user','admin']} name!: string
});
@Column({ name: 'last_name', type: 'varchar', length:30,nullable: false })
surname!: string
// How does next's type defined?
UserSchema.pre('save', async function(next:any):Promise<void>{ @Column({ name: 'last_name', type: 'varchar', length:30,nullable: false })
if(!this.isModified('password')) return next(); displayName!: string
console.log('next', next)
const salt = await bcrypt.genSalt(SALT_WORK_FACTOR); @Column({ type: 'varchar',length:20, unique: true, nullable: false })
const hash = await bcrypt.hash(this.password, salt); email!: string
this.password = hash;
next(); @Column({ type: 'varchar',length:10, unique: true })
phone!: string
@Column({ type: 'varchar', nullable: false })
password!: string
@CreateDateColumn()
// @CreateDateColumn({ name: 'created_at', type: Date, default: new Date() })
// createdAt: Date
@Column({
type: "enum",
enum: ["worker", "director"],
default: "ghost"
}) })
role!: UserRoleType
UserSchema.set('toJSON',{
transform:(doc:any, ret:any, options:any)=>{ @BeforeInsert()
delete ret.password; protected async beforeInserthashPassword():Promise<void> {
return ret; const salt = await bcrypt.genSalt(SALT_WORK_FACTOR);
this.password = await bcrypt.hash(this.password, salt);
} }
})
UserSchema.methods.checkPassword =function(password:string):Promise<boolean>{ @BeforeUpdate()
return bcrypt.compare(password,this.password); protected async beforeUpdateHashPassword():Promise<void> {
} const salt = await bcrypt.genSalt(SALT_WORK_FACTOR);
this.password = await bcrypt.hash(this.password, salt);
}
UserSchema.methods.generateToken =function(){
this.token=nanoid();
} }
// 3. Create a Model.
const User = model<IUser>('User', UserSchema);
export default User;
// const UserEntity = new EntitySchema<IUser>({
// name: "user",
// columns: {
// id: {
// type: "uuid",
// primary: true,
// generated: "uuid",
// },
// name: {
// nullable: false,
// type: String,
// length: 20,
// },
// surname: {
// nullable: false,
// type: String,
// length: 50,
// },
// password: {
// nullable: false,
// type: String,
// },
// email: {
// nullable: false,
// type: String,
// },
// displayName: {
// nullable: false,
// type: String,
// },
// role: {
// type: String,
// default: "user",
// enum: ["director","user"]
// },
// createdAt: {
// type: Date,
// default: Date.now(),
// },
// methods?:{
// type:String
// }
// },
// relations: {
// tasks: {
// type: "many-to-many",
// target: "category", // CategoryEntity
// },
// },
// })
// UserEntity.methods.checkPassword=function(password:string):Promise<boolean> {
// return bcrypt.compare(password,this.password);
// }
// export default UserEntity
// import { Schema, model } from 'mongoose';
// import bcrypt from 'bcrypt';
// import {nanoid} from 'nanoid';
// const SALT_WORK_FACTOR= 10;
// // 1. Create an interface representing a document in MongoDB.
// interface IUser {
// name: string;
// surname: string;
// email: string;
// displayName: string;
// password:string;
// role: string;
// }
// // 2. Create a Schema corresponding to the document interface.
// const UserSchema = new Schema<IUser>({
// name: { type: String, required: true },
// surname: { type: String, required: true },
// email: { type: String, required: true },
// displayName: { type: String, required: true },
// password: { type: String, required: true },
// role:{type:String,default: 'user',enum:['user','admin']}
// });
// // How does next's type defined?
// UserSchema.pre('save', async function(next:any):Promise<void>{
// if(!this.isModified('password')) return next();
// console.log('next', next)
// const salt = await bcrypt.genSalt(SALT_WORK_FACTOR);
// const hash = await bcrypt.hash(this.password, salt);
// this.password = hash;
// next();
// })
// UserSchema.set('toJSON',{
// transform:(doc:any, ret:any, options:any)=>{
// delete ret.password;
// return ret;
// }
// })
// UserSchema.methods.checkPassword =function(password:string):Promise<boolean>{
// return bcrypt.compare(password,this.password);
// }
// UserSchema.methods.generateToken =function(){
// this.token=nanoid();
// }
// // 3. Create a Model.
// const User = model<IUser>('User', UserSchema);
// export default User;
import express,{Router, Request, Response} from 'express'; import express,{Router, Request, Response} from 'express';
import User from '../models/User'; import {User} from '../models/User';
// import {DataSource} from 'typeorm';
import {myDataSource} from '../app-data-source';
const router:Router = express.Router(); const router:Router = express.Router();
const dataSource = myDataSource;
router.post('/', async (req : Request, res : Response) => { router.get('/', async (req : Request, res : Response):Promise<object> => {
try{ const users:any = await dataSource.manager.find(User)
return res.send({users})
})
router.post('/', async (req : Request, res : Response):Promise<object> => {
const {name,surname,password,email} = req.body; const {name,surname,password,email} = req.body;
const displayName = surname+' '+name[0]+'.' const displayName = surname+' '+name[0]+'.'
const user = new User({ const user = new User();
name:name, user.name = name;
surname:surname, user.surname = surname;
email:email, user.password = password;
password:password, user.displayName= displayName;
displayName:displayName user.email = email;
})
await user.save(); await user.save();
return res.send({user}) return res.send({user})
}catch(e ){
if (e instanceof Error){
return res.status(404).send({'message':e.message});
}
return res.status(500).send({'message':'Broke server'});
}
}) })
router.get('/', async (req : Request, res : Response):Promise<Response<any, Record<string, any>>> => {
const users = await User.find()
return res.send({users}) // router.post('/', async (req : Request, res : Response) => {
}) // try{
// const {name,surname,password,email} = req.body;
// const displayName = surname+' '+name[0]+'.'
// await User.insert({
// name:name,
// surname:surname,
// email:email,
// password:password,
// displayName:displayName
// })
// const user:User = new User({
// name:name,
// surname:surname,
// email:email,
// password:password,
// displayName:displayName
// })
// await user.save();
// return res.send({message:'created user'})
// }catch(e ){
// if (e instanceof Error){
// return res.status(404).send({'message':e.message});
// }
// return res.status(500).send({'message':'Broke server'});
// }
// })
// router.get('/', async (req : Request, res : Response):Promise<Response<any, Record<string, any>>> => {
// const users = await User.find()
// return res.send({users})
// })
export default router; export default router;
import express, { Express } from 'express'; import express, { Express } from 'express';
import cors from 'cors'; import cors from 'cors';
import mongoose from 'mongoose';
import users from './routers/users'; import users from './routers/users';
import {myDataSource} from './app-data-source';
console.log('Hello world!');
myDataSource
.initialize()
.then(() => {
console.log("Data Source has been initialized!")
})
.catch((err) => {
console.error("Error during Data Source initialization:", err)
})
const app:Express = express(); const app:Express = express();
app.use(express.static('public')); app.use(express.static('public'));
...@@ -13,16 +21,13 @@ const PORT = 8000; ...@@ -13,16 +21,13 @@ const PORT = 8000;
app.use('/users',users) app.use('/users',users)
const run = async() => { const run = async() => {
mongoose.connect(`mongodb://localhost:27017/task-planner`);
app.listen(PORT, () => { app.listen(PORT, () => {
console.log(`Server started at http://localhost:${PORT}/`); console.log(`Server started at http://localhost:${PORT}/`);
}) })
process.on("exit", () => {
mongoose.disconnect();
})
} }
console.log('Hello world!');
run().catch(console.error); run().catch(console.error);
\ No newline at end of file
{ {
"compilerOptions": { "compilerOptions": {
"experimentalDecorators": true,
/* Visit https://aka.ms/tsconfig to read more about this file */ /* Visit https://aka.ms/tsconfig to read more about this file */
/* Projects */ /* Projects */
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment