Разделение методов создания и обновления элементов, добавление полей author, description, service_name. Исправление бага при котором не удалялось апи. Удаление из ответа лишних полей __v и _id

This commit is contained in:
vigdorov
2020-07-10 15:55:10 +03:00
parent 2a671f30d0
commit 89cf9d0c84
6 changed files with 148 additions and 59 deletions

View File

@ -1,8 +1,15 @@
import {Model} from 'mongoose';
import {Injectable, NotFoundException} from '@nestjs/common';
import {Injectable, NotFoundException, BadGatewayException} from '@nestjs/common';
import {InjectModel} from '@nestjs/mongoose';
import {Store, StoreRequest} from './store.schema';
const validateModel = async (store: Store) => {
try {
await store.validate();
} catch (e) {
throw new BadGatewayException(e);
}
};
@Injectable()
export class StoreService {
@ -14,25 +21,51 @@ export class StoreService {
async create(store: StoreRequest): Promise<Store> {
const searchStore = await this.findOne(store.key);
if (searchStore) {
return searchStore.updateOne(store);
} else {
const createdStore = new this.storeModel(store);
return createdStore.save();
throw new NotFoundException(`Api key ${store.key} is already taken`);
}
const createdStore = new this.storeModel(store);
await validateModel(createdStore);
return createdStore.save();
}
async update({author, ...omitProps}: StoreRequest): Promise<Store> {
const searchStore = await this.findOne(omitProps.key);
if (searchStore) {
const store = {
...omitProps,
author: searchStore.author,
};
const updateStore = new this.storeModel(store);
await validateModel(updateStore);
await searchStore.updateOne({
...store,
author: searchStore.author,
});
return updateStore;
}
throw new NotFoundException(`Not Found api key - ${omitProps.key}`);
}
async findOne(key: string): Promise<Store> {
return this.storeModel.findOne({key});
return this.storeModel.findOne({key})
}
async removeOne(key: string): Promise<string> {
async removeOne(key: string): Promise<Store> {
const searchStore = await this.findOne(key);
if (searchStore) {
await searchStore.remove();
return 'ok';
await this.storeModel.deleteOne({key});
return searchStore;
}
throw new NotFoundException(`Not Found key - ${key}`);