88 lines
2.7 KiB
TypeScript
88 lines
2.7 KiB
TypeScript
import {Model, Connection} from 'mongoose';
|
|
import {Injectable, NotFoundException, BadGatewayException} from '@nestjs/common';
|
|
import {InjectConnection} from '@nestjs/mongoose';
|
|
import {Store, StoreRequest, StoreSchema} from './store.schema';
|
|
import {DB_TEST_NAME, DB_NAME, COOLECTION_STORE} from 'src/consts';
|
|
|
|
const validateModel = async (store: Store) => {
|
|
try {
|
|
await store.validate();
|
|
} catch (e) {
|
|
throw new BadGatewayException(e);
|
|
}
|
|
};
|
|
|
|
@Injectable()
|
|
export class StoreService {
|
|
constructor(
|
|
@InjectConnection(DB_NAME) private dbConnection: Connection,
|
|
@InjectConnection(DB_TEST_NAME) private dbTestConnection: Connection,
|
|
) {}
|
|
|
|
storeModel(api: string): Model<Store> {
|
|
if (api === DB_TEST_NAME) {
|
|
return this.dbTestConnection.model<Store>(COOLECTION_STORE, StoreSchema);
|
|
}
|
|
return this.dbConnection.model<Store>(COOLECTION_STORE, StoreSchema);
|
|
}
|
|
|
|
async findAll(api: string): Promise<Store[]> {
|
|
return this.storeModel(api).find().exec();
|
|
}
|
|
|
|
async create(api: string, store: StoreRequest): Promise<Store> {
|
|
const searchStore = await this.findOne(api, store.key);
|
|
|
|
if (searchStore) {
|
|
throw new NotFoundException(`Api key ${store.key} is already taken`);
|
|
}
|
|
|
|
const createdStore = new (this.storeModel(api))(store);
|
|
|
|
await validateModel(createdStore);
|
|
|
|
const savedStore = await createdStore.save();
|
|
if (!Object.keys(savedStore.value).length) {
|
|
await savedStore.updateOne(store);
|
|
}
|
|
return savedStore;
|
|
}
|
|
|
|
async update(api: string, {author, ...omitProps}: StoreRequest): Promise<Store> {
|
|
const searchStore = await this.findOne(api, omitProps.key);
|
|
|
|
if (searchStore) {
|
|
const store = {
|
|
...omitProps,
|
|
author: searchStore.author,
|
|
};
|
|
const updateStore = new (this.storeModel(api))(store);
|
|
await validateModel(updateStore);
|
|
|
|
await searchStore.updateOne({
|
|
...store,
|
|
author: searchStore.author,
|
|
});
|
|
|
|
return updateStore;
|
|
}
|
|
|
|
throw new NotFoundException(`Not Found api key - ${omitProps.key}`);
|
|
}
|
|
|
|
async findOne(api: string, key: string): Promise<Store> {
|
|
return this.storeModel(api).findOne({key})
|
|
}
|
|
|
|
async removeOne(api: string, key: string): Promise<Store> {
|
|
const searchStore = await this.findOne(api, key);
|
|
|
|
if (searchStore) {
|
|
await this.storeModel(api).deleteOne({key});
|
|
|
|
return searchStore;
|
|
}
|
|
|
|
throw new NotFoundException(`Not Found key - ${key}`);
|
|
}
|
|
} |