alessandro trinca tornidor commited on
Commit
fdefa6c
·
1 Parent(s): 59af081

feat: add /thesaurus-custom/{word} to delete words

Browse files
my_ghost_writer/app.py CHANGED
@@ -303,6 +303,19 @@ async def add_custom_synonyms(body: CustomSynonymRequest):
303
  raise HTTPException(status_code=500, detail=f"Failed to add custom synonyms: {str(e)}")
304
 
305
 
 
 
 
 
 
 
 
 
 
 
 
 
 
306
  @app.exception_handler(HTTPException)
307
  def http_exception_handler(request: Request, exc: HTTPException) -> JSONResponse:
308
  origin = request.headers.get("origin")
 
303
  raise HTTPException(status_code=500, detail=f"Failed to add custom synonyms: {str(e)}")
304
 
305
 
306
+ @app.delete("/thesaurus-custom/{word}")
307
+ async def delete_custom_synonyms(word: str):
308
+ """Deletes custom synonyms for a given word from the in-memory store."""
309
+ try:
310
+ custom_synonym_handler.delete_entry(word)
311
+ return {"message": f"Synonyms for '{word}' deleted successfully (in-memory)."}
312
+ except KeyError as e:
313
+ raise HTTPException(status_code=404, detail=str(e))
314
+ except Exception as e:
315
+ app_logger.error(f"Error deleting custom synonyms: {e}")
316
+ raise HTTPException(status_code=500, detail=f"Failed to delete custom synonyms: {str(e)}")
317
+
318
+
319
  @app.exception_handler(HTTPException)
320
  def http_exception_handler(request: Request, exc: HTTPException) -> JSONResponse:
321
  origin = request.headers.get("origin")
my_ghost_writer/custom_synonym_handler.py CHANGED
@@ -15,6 +15,14 @@ class CustomSynonymHandler:
15
  self.lexicon[word][relation_type] = related_words
16
  self._update_inverted_index(word, relation_type, related_words)
17
 
 
 
 
 
 
 
 
 
18
  def get_related(self, word: str, relation_type: str) -> list[dict[str, Any]]:
19
  word = word.lower()
20
  if word in self.lexicon and relation_type in self.lexicon[word]:
 
15
  self.lexicon[word][relation_type] = related_words
16
  self._update_inverted_index(word, relation_type, related_words)
17
 
18
+ def delete_entry(self, word: str):
19
+ """Deletes a custom synonym entry if it exists."""
20
+ word_lower = word.lower()
21
+ if word_lower in self.lexicon:
22
+ del self.lexicon[word_lower]
23
+ else:
24
+ raise KeyError(f"No custom synonyms found for word '{word}'.")
25
+
26
  def get_related(self, word: str, relation_type: str) -> list[dict[str, Any]]:
27
  word = word.lower()
28
  if word in self.lexicon and relation_type in self.lexicon[word]:
static/tests/test-helper.ts CHANGED
@@ -419,7 +419,6 @@ export async function openMobileMenu(page: Page, msg: string) {
419
  }
420
  }
421
 
422
-
423
  export async function standardCheck(page: Page, projectName: string, expectedString: string, testName: string, click: boolean = true) {
424
  // start as a normal test
425
  if (click) await page.getByRole('button', { name: 'id-perform-wordsearch' }).click();
@@ -434,4 +433,52 @@ export async function standardCheck(page: Page, projectName: string, expectedStr
434
  await page.getByLabel('id-div-candidate-1-nth').click();
435
  await assertVisibleTextAfterNavigation(page, 'id-div-1-range-1-nth', expectedString, "bottom", "gametext", projectName);
436
  await page.waitForTimeout(200)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
437
  }
 
419
  }
420
  }
421
 
 
422
  export async function standardCheck(page: Page, projectName: string, expectedString: string, testName: string, click: boolean = true) {
423
  // start as a normal test
424
  if (click) await page.getByRole('button', { name: 'id-perform-wordsearch' }).click();
 
433
  await page.getByLabel('id-div-candidate-1-nth').click();
434
  await assertVisibleTextAfterNavigation(page, 'id-div-1-range-1-nth', expectedString, "bottom", "gametext", projectName);
435
  await page.waitForTimeout(200)
436
+ }
437
+
438
+ export async function deleteCustomSynonym(word: string) {
439
+ // The URL of your backend endpoint.
440
+ // Make sure the port (7860) matches your server configuration.
441
+ const apiUrl = `http://localhost:7860/thesaurus-custom/${word}`;
442
+
443
+ try {
444
+ // 1. Await the fetch call to complete.
445
+ const response = await fetch(apiUrl, {
446
+ method: 'DELETE',
447
+ headers: {
448
+ 'Content-Type': 'application/json',
449
+ },
450
+ });
451
+
452
+ // 2. Await the parsing of the JSON body.
453
+ const responseData = await response.json();
454
+
455
+ // 3. Check if the request was successful.
456
+ if (!response.ok) {
457
+ // If not, throw an error with details from the server's response.
458
+ throw new Error(`HTTP error! Status: ${response.status}, Detail: ${responseData.detail}`);
459
+ }
460
+
461
+ // 4. Handle the successful response data.
462
+ console.log('Success:', responseData);
463
+
464
+ // You can now access the message property directly for assertions.
465
+ const message = responseData.message;
466
+ console.log('Message from server:', message);
467
+
468
+ // Example of an assertion similar to your Playwright test:
469
+ if (message.includes(`Synonyms for '${word}' deleted successfully`)) {
470
+ console.log('Assertion passed: The message content is correct.');
471
+ } else {
472
+ console.error('Assertion failed: The message content is incorrect.');
473
+ }
474
+
475
+ return responseData; // Return the data for further use.
476
+
477
+ } catch (error) {
478
+ // Handle any errors that occurred during the fetch operation.
479
+ console.error('Error:', error);
480
+ // Example: alert('Error: ' + error.message);
481
+ // Re-throw the error if you want calling functions to handle it.
482
+ throw error;
483
+ }
484
  }