From 93398c827911f33140b7347166efc54c3175d6f0 Mon Sep 17 00:00:00 2001 From: Lauren Liberda Date: Mon, 19 Jul 2021 23:29:59 +0200 Subject: [PATCH] fix closure table saves on item creation --- src/items/items.service.ts | 39 +++++++++++++++++++------------------- tsconfig.json | 2 +- 2 files changed, 20 insertions(+), 21 deletions(-) diff --git a/src/items/items.service.ts b/src/items/items.service.ts index ed3486a..8a70f95 100644 --- a/src/items/items.service.ts +++ b/src/items/items.service.ts @@ -44,34 +44,33 @@ export class ItemsService { } async createItem(input: NewItemInput): Promise { + // must use Repository.save() for the closure table to work, + // so we have to check whether the provided ID exists in the first place + if (input.id && (await this.itemRepository.count({ id: input.id })) !== 0) { + throw new Error('Item with this ID already exists'); + } + + const highestId = input.id + ? // nobody cares in this case + null + : ( + await this.itemRepository.findOne({ + select: ['id'], + order: { id: 'DESC' }, + }) + )?.id || '139999999999'; + const item = this.itemRepository.create({ ...input, - id: input.id || undefined, + // if id not provided, use the highest one in db +1 + id: highestId ? (BigInt(highestId) + 1n).toString(10) : input.id, parent: input.parent ? await this.itemRepository.findOneOrFail(input.parent) : undefined, }); - const highestIdQuery = this.itemRepository - .createQueryBuilder() - .select('id') - .orderBy('id', 'DESC') - .limit(1); + await this.itemRepository.save(item); - const insert = await this.itemRepository - .createQueryBuilder() - .insert() - .into(Item) - .values({ - ...item, - // if id is specified, use it. - // if not, get the highest id in table and use highest_id+1 - id: input.id || (() => `((${highestIdQuery.getSql()}) + 1)`), - }) - .returning(['id']) - .execute(); - - item.id = insert.identifiers[0].id || item.id; return item; } } diff --git a/tsconfig.json b/tsconfig.json index 6edebb6..f3f2bd8 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -5,7 +5,7 @@ /* Basic Options */ "incremental": true /* Enable incremental compilation */, - "target": "es2017" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */, + "target": "es2020" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */, "module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */, // "lib": [], /* Specify library files to be included in the compilation. */ // "allowJs": true, /* Allow javascript files to be compiled. */