61 lines
2.8 KiB
TypeScript
61 lines
2.8 KiB
TypeScript
import { Get, Inject, Injectable, Param } from '@nestjs/common';
|
|
import { createClient } from 'redis';
|
|
import { Entity, Repository, Schema } from 'redis-om';
|
|
import { ListingCriteria } from '../models/main.model.js';
|
|
import { REDIS_CLIENT } from '../redis/redis.module.js';
|
|
import { FileService } from '../file/file.service.js';
|
|
import { User } from 'src/models/db.model.js';
|
|
import { WINSTON_MODULE_PROVIDER } from 'nest-winston';
|
|
import { Logger } from 'winston';
|
|
import { PG_CONNECTION } from 'src/drizzle/schema.js';
|
|
import { NodePgDatabase } from 'drizzle-orm/node-postgres/driver.js';
|
|
import * as schema from '../drizzle/schema.js';
|
|
import { eq, sql,and } from 'drizzle-orm';
|
|
|
|
@Injectable()
|
|
export class UserService {
|
|
constructor(@Inject(WINSTON_MODULE_PROVIDER) private readonly logger: Logger,
|
|
@Inject(PG_CONNECTION) private conn: NodePgDatabase<typeof schema>,private fileService:FileService) {
|
|
}
|
|
private getConditions(criteria: ListingCriteria): any[] {
|
|
const conditions = [];
|
|
if (criteria.state) {
|
|
conditions.push(sql`EXISTS (SELECT 1 FROM unnest(users."areasServed") AS area WHERE area LIKE '%' || ${criteria.state} || '%')`);
|
|
}
|
|
return conditions;
|
|
}
|
|
async getUserByMail( id:string){
|
|
const users = await this.conn.select().from(schema.users).where(sql`email = ${id}`) as User[]
|
|
const user = users[0]
|
|
user.hasCompanyLogo=this.fileService.hasCompanyLogo(id);
|
|
user.hasProfile=this.fileService.hasProfile(id);
|
|
return user;
|
|
}
|
|
async getUserById( id:string){
|
|
const users = await this.conn.select().from(schema.users).where(sql`id = ${id}`) as User[]
|
|
const user = users[0]
|
|
user.hasCompanyLogo=this.fileService.hasCompanyLogo(id);
|
|
user.hasProfile=this.fileService.hasProfile(id);
|
|
return user;
|
|
}
|
|
async saveUser(user:any):Promise<User>{
|
|
if (user.id){
|
|
const [updateUser] = await this.conn.update(schema.users).set(user).where(eq(schema.users.id, user.id)).returning();
|
|
return updateUser as User;
|
|
} else {
|
|
const [newUser] = await this.conn.insert(schema.users).values(user).returning();
|
|
return newUser as User;
|
|
}
|
|
}
|
|
async findUser(criteria:ListingCriteria){
|
|
const start = criteria.start ? criteria.start : 0;
|
|
const length = criteria.length ? criteria.length : 12;
|
|
const conditions = this.getConditions(criteria)
|
|
const [data, total] = await Promise.all([
|
|
this.conn.select().from(schema.users).where(and(...conditions)).offset(start).limit(length),
|
|
this.conn.select({ count: sql`count(*)` }).from(schema.users).where(and(...conditions)).then((result) => Number(result[0].count)),
|
|
]);
|
|
return { total, data };
|
|
}
|
|
|
|
} |