2023-03-12 02:13:59 +01:00
|
|
|
import { JobService } from "@apricote/nest-pg-boss";
|
2020-02-01 16:11:48 +01:00
|
|
|
import { Injectable, NotFoundException } from "@nestjs/common";
|
2023-03-12 02:13:59 +01:00
|
|
|
import { IImportSpotifyJob, ImportSpotifyJob } from "../sources/jobs";
|
2020-09-05 21:07:05 +02:00
|
|
|
import { SpotifyConnection } from "../sources/spotify/spotify-connection.entity";
|
2020-02-01 16:11:48 +01:00
|
|
|
import { CreateOrUpdateDto } from "./dto/create-or-update.dto";
|
|
|
|
|
import { User } from "./user.entity";
|
|
|
|
|
import { UserRepository } from "./user.repository";
|
|
|
|
|
|
|
|
|
|
@Injectable()
|
|
|
|
|
export class UsersService {
|
2023-03-12 02:13:59 +01:00
|
|
|
constructor(
|
|
|
|
|
private readonly userRepository: UserRepository,
|
|
|
|
|
@ImportSpotifyJob.Inject()
|
|
|
|
|
private readonly importSpotifyJobService: JobService<IImportSpotifyJob>
|
|
|
|
|
) {}
|
2020-02-01 16:11:48 +01:00
|
|
|
|
|
|
|
|
async findById(id: string): Promise<User> {
|
2022-06-25 13:48:25 +00:00
|
|
|
const user = await this.userRepository.findOneBy({ id });
|
2020-02-01 16:11:48 +01:00
|
|
|
|
|
|
|
|
if (!user) {
|
|
|
|
|
throw new NotFoundException("UserNotFound");
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return user;
|
|
|
|
|
}
|
|
|
|
|
|
2020-02-02 19:21:58 +01:00
|
|
|
async findAll(): Promise<User[]> {
|
|
|
|
|
return this.userRepository.find();
|
|
|
|
|
}
|
|
|
|
|
|
2020-02-01 16:11:48 +01:00
|
|
|
async createOrUpdate(data: CreateOrUpdateDto): Promise<User> {
|
2022-06-25 13:48:25 +00:00
|
|
|
let user = await this.userRepository.findOneBy({
|
|
|
|
|
spotify: { id: data.spotify.id },
|
2020-02-01 16:11:48 +01:00
|
|
|
});
|
|
|
|
|
|
2023-03-12 02:13:59 +01:00
|
|
|
const isNew = !user;
|
|
|
|
|
if (isNew) {
|
2020-02-01 16:11:48 +01:00
|
|
|
user = this.userRepository.create({
|
|
|
|
|
spotify: {
|
2020-05-02 17:17:20 +02:00
|
|
|
id: data.spotify.id,
|
|
|
|
|
},
|
2020-02-01 16:11:48 +01:00
|
|
|
});
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
user.spotify.accessToken = data.spotify.accessToken;
|
|
|
|
|
user.spotify.refreshToken = data.spotify.refreshToken;
|
|
|
|
|
user.displayName = data.displayName;
|
|
|
|
|
user.photo = data.photo;
|
|
|
|
|
|
|
|
|
|
await this.userRepository.save(user);
|
|
|
|
|
|
2023-03-12 02:13:59 +01:00
|
|
|
if (isNew) {
|
|
|
|
|
// Make sure that existing listens are crawled immediately
|
|
|
|
|
this.importSpotifyJobService.sendOnce({ userID: user.id }, {}, user.id);
|
|
|
|
|
}
|
|
|
|
|
|
2020-02-01 16:11:48 +01:00
|
|
|
return user;
|
|
|
|
|
}
|
2020-02-02 19:21:58 +01:00
|
|
|
|
|
|
|
|
async updateSpotifyConnection(
|
|
|
|
|
user: User,
|
|
|
|
|
spotify: SpotifyConnection
|
|
|
|
|
): Promise<void> {
|
2021-05-25 18:12:42 +02:00
|
|
|
// eslint-disable-next-line no-param-reassign
|
2020-02-02 19:21:58 +01:00
|
|
|
user.spotify = spotify;
|
|
|
|
|
await this.userRepository.save(user);
|
|
|
|
|
}
|
2020-02-01 16:11:48 +01:00
|
|
|
}
|