Compare commits

...
Author SHA1 Message Date
kallweit 6c2e3fab04 Merge remote-tracking branch 'origin/dev' into feature/preprocessing
LocationBasedServices/smartguide/pipeline/pr-dev Build queued...
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-25 15:15:40 +02:00
kallweit e5283543a1 feat(news): store matched OpenAlex topics in 'aktuell_openalex_topics' index
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-25 13:48:57 +02:00
farajollahi 4805fe9c3c Merge pull request 'fix-analyses-dashboard' (#241) from fix-analyses-dashboard into dev
LocationBasedServices/smartguide/pipeline/head This commit looks good
Reviewed-on: #241
2026-07-24 21:07:04 +02:00
Louis 02b498f829 fix(jobs): write a clear system log message when a run fails to pull or start
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-24 15:34:03 +02:00
Louis 18f661e3b4 docs(jobs): document the UI create/edit workflow
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-24 14:55:24 +02:00
kallweit 22bfb2feba Merge branch 'feature/preprocessing' of https://project.nes.uni-due.de/gitea/lbs/smartguide into feature/preprocessing
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-24 14:33:47 +02:00
kallweit 358a47bbf5 feat(jobs): remove individual demo image creation 2026-07-24 14:33:21 +02:00
Louis ceed96102f style(jobs): center and enlarge the health status dot
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-24 14:32:51 +02:00
Louis 467f40a625 feat(jobs): name job containers after the job instead of its id 2026-07-24 14:27:04 +02:00
Louis e8b5dcfd5b feat(jobs): fail the run when a registry image can't be pulled instead of using a local copy
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-24 14:12:22 +02:00
Louis f0caacd696 feat(jobs): show Nexus registry reachability next to the Docker daemon 2026-07-24 14:05:37 +02:00
Louis 9d24c0a9bb fix(jobs): start the new-job image field empty instead of prefilled
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-24 13:20:12 +02:00
kallweit 82d2c508b8 feat(jobs): add per-job dockerfiles and requirements and unify logging format
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-23 22:59:06 +02:00
kallweit ddbf000213 feat(jobs): fix table to not go out-of-bounds anymore during window resizing 2026-07-23 14:00:17 +02:00
Louis ee98b589c9 add Nexus registry credentials for job image listing
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-23 12:13:49 +02:00
Louis 4e0afc12ed feat(jobs): select image from a Nexus autocomplete 2026-07-23 12:03:33 +02:00
Louis fa68c338c2 pause polling and live ticker while no job is active 2026-07-23 11:59:46 +02:00
Louis 0712d3f3fa skip redundant initial task fetch 2026-07-23 11:21:41 +02:00
Louis 6cccd6d19f fix(jobs): keep last-run details on single lines
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-21 18:25:07 +02:00
Louis 16f7e665fe fix(jobs): keep cron expression on one line in schedule column 2026-07-21 18:19:07 +02:00
Louis e78b406d6d fix(jobs): only show enabled badge for scheduled jobs 2026-07-21 18:19:07 +02:00
Louis 292c02cac8 feat(jobs): allow renaming a job in the edit dialog 2026-07-21 18:18:53 +02:00
Louis ff322fc29b feat(jobs): show run duration and live elapsed time 2026-07-21 18:18:52 +02:00
Louis 1a01ff5198 fix(jobs): keep log scroll position on refresh 2026-07-21 18:18:52 +02:00
Louis c47d5ee170 fix(jobs): keep new-job button on one line, unclip name label, make command/image fields resizable 2026-07-21 18:18:51 +02:00
Louis afaa840d48 feat(jobs): add edit dialog with hover pencil in the name column 2026-07-21 18:18:35 +02:00
Louis fb44e9db3c style(background-jobs): trim Dockerfile comments 2026-07-21 18:18:32 +02:00
Louis 762e3f9a15 refactor(background-jobs): copy full script tree into image and move demo job 2026-07-21 18:18:32 +02:00
Louis 0b3be35885 feat(jobs): prefill default image and add field tooltips in create-dialog
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-21 06:24:58 +02:00
Louis 5323797c71 refactor(background-jobs): move image definition to service/scripts/jobs-image 2026-07-21 06:12:41 +02:00
kallweit 85e79aeb3e Merge branch 'feature/preprocessing' of https://project.nes.uni-due.de/gitea/lbs/smartguide into feature/preprocessing
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-21 00:32:56 +02:00
kallweit 83ed0bcaee fix(jobs): don't count empty keyword extractions as successful 2026-07-21 00:29:59 +02:00
kallweit 807adbd6e4 feat(jobs): add news topic-mapping as background job 2026-07-21 00:28:18 +02:00
kallweit 8db323d605 feat(news): store matched topics in aktuell_postproc and switch to topic batch mapping 2026-07-20 23:43:33 +02:00
Louis 712fcbb749 refactor(background-jobs): remove entrypoint.sh and discovery
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-20 22:17:52 +02:00
Louis cb5a887d12 docs(background-jobs): update readme 2026-07-20 22:17:37 +02:00
Louis 755f83f65a refactor(jobs): simplify create-dialog to free-text command 2026-07-20 22:17:35 +02:00
Louis 4bd4a015f1 refactor(jobs): remove job definition seeding 2026-07-20 22:17:31 +02:00
Louis 55d0b7918f Merge remote-tracking branch 'origin/dev' into feature/preprocessing
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-17 15:34:47 +02:00
Louis b22f16809d feat(jobs): add job deletion with confirmation
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-17 14:45:46 +02:00
Louis b9c4067250 fix(jobs): display UTC timestamps in local time
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-17 14:35:20 +02:00
Louis 90860230f4 feat(jobs): add user-friendly scheduling presets with advanced cron support
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-17 14:18:28 +02:00
Louis d005162a80 fix(jobs): auto-refresh logs and improve job table layout 2026-07-17 13:54:59 +02:00
Louis 0f65a0f589 fix(jobs): make container runs and logs consistent 2026-07-17 13:38:58 +02:00
kallweit b39daba561 feat(jobs): add stop button
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-17 00:50:07 +02:00
kallweit 53155d4e53 feat(logs): add run dropdown, visible scrollbar and download button 2026-07-17 00:30:33 +02:00
kallweit 8583f6622e feat(jobs): cap logs at last 200 lines 2026-07-16 23:16:55 +02:00
kallweit 93481bf9c5 feat(jobs): authenticate registry image pulls 2026-07-16 22:22:11 +02:00
kallweit a76789f34b fix(config): load .env relative to config.py 2026-07-16 22:21:04 +02:00
kallweit 2566fa9208 feat(jobs): add news-crawler, bund-crawler and topic-mapper jobs 2026-07-16 20:41:42 +02:00
Louis e92b450e5b backgroundjobs: add demo jobs at startup
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-15 23:57:43 +02:00
Louis 5d72140758 backgroundjobs: pull job image from registry before each run
LocationBasedServices/smartguide/pipeline/head This commit looks good
2026-07-15 23:50:27 +02:00
Louis bee19dfa39 backgroundjobs: let superadmins define image, command and env per job 2026-07-15 20:49:57 +02:00
Louis 3b4d0b3339 allow superadmins to create and delete whitelisted job schedules
LocationBasedServices/smartguide/pipeline/head There was a failure building this commit
2026-07-14 19:04:59 +02:00
Louis e5f28f2143 add short demo jobs for demos and parallel testing 2026-07-14 19:04:59 +02:00
kallweit 069566d71d feat(jobs): rename 'preprocessing' to 'jobs', wire-up backend to frontend 2026-07-14 19:04:59 +02:00
Louis 07278b3f65 add generated background jobs api client 2026-07-14 19:04:59 +02:00
Louis 3684a5acf5 mount docker socket in serve task for job runner 2026-07-14 19:02:40 +02:00
Louis 5ce97e6854 add superadmin background job endpoints and scheduler 2026-07-14 19:02:40 +02:00
Louis 8bb0cf18ad add docker job runner and scheduler 2026-07-14 19:02:40 +02:00
Louis 19933d69b6 add background job definition and run tables with seeding 2026-07-14 19:02:40 +02:00
Louis 9aeb8171a7 rename preprocessing worker folder to background-jobs 2026-07-14 19:02:40 +02:00
kallweit f4542d21b8 feat(preprocessing): revert login bypass 2026-07-14 19:02:40 +02:00
kallweit 532c94b00b feat(preprocessing): add first version of preprocessing, dockerize news job processing 2026-07-14 19:02:40 +02:00
kallweit 5d1d62acb8 feat(preprocessing): initial mock page for preprocessing 2026-07-14 19:02:40 +02:00
377 changed files with 24720 additions and 11299 deletions
+15
View File
@@ -0,0 +1,15 @@
*
!background-jobs
!service
service/*
!service/scripts
# Data-only folders that do not belong in the job image.
service/scripts/multipliers
**/__pycache__
**/*.pyc
**/.venv
**/.env
**/.env.*
**/out
+5
View File
@@ -0,0 +1,5 @@
.env
.env.*
__pycache__/
*.pyc
.venv/
+7
View File
@@ -0,0 +1,7 @@
# Copy this file to `.env` and fill in the real values.
# `.env` is gitignored and is NOT baked into the image.
INSE_ELASTIC_URL=https://inse.nes.uni-due.de/elastic
INSE_ELASTIC_API_KEY=your-elastic-api-key-here
INSE_LLM_BASE_URL=https://project.nes.uni-due.de/llm2/v1/
INSE_LLM_API_KEY=your-llm-api-key-here
INSE_LLM_MODEL=gemma4-e4b
+5
View File
@@ -0,0 +1,5 @@
# Local secrets – never commit
.env
__pycache__/
*.pyc
+95
View File
@@ -0,0 +1,95 @@
# Background Jobs
Background Jobs sind Docker-Container, die regelmäßig oder manuell Elasticsearch-Daten verarbeiten. Sie werden vom Backend über den Docker-Socket gestartet.
**Wichtig:** Jobs sind in der **Datenbank**, nicht im Image. Das Image enthält nur die ausführbaren Skripte.
## Jobs anlegen
**Frontend** (`/jobs`):
- "Neuer Job" → Name + Command + optionales Image + Zeitplan
**API**:
```bash
curl -X POST -H "Authorization: Bearer $TOKEN" \
-d '{"name": "Sync", "command": "python sync.py --sync-delta", "schedule": "0 3 * * *"}' \
http://localhost:8000/api/background-jobs/tasks
```
Command-Beispiele:
```
python service/scripts/demo/demo.py 20
python sync.py --sync-delta
python service/scripts/news/ude/run_pipeline.py --skip-upload --max-items 5
python -m service.scripts.news.topic_mapper.map_news_topics --output-index docker-job_test --max-docs 50
python -m service.scripts.projects.topic_mapper.map_project_topics --dry-run
sh -c "cd service/scripts/projects/bund && python gpc.data.py --skip-upload"
```
**Neue Jobs = kein Image-Rebuild.** Die Skripte sind bereits im Image; der Command wird direkt an Docker übergeben.
## Image & Dockerfile
Das [Dockerfile](../service/scripts/jobs-image/Dockerfile) kopiert den kompletten `service/scripts/`-Baum (Pfade im Container = Pfade im Repo) plus `background-jobs/app/` (sync.py) und hat keinen ENTRYPOINT. Neue Skripte unter `service/scripts` landen automatisch im nächsten Build — ohne Dockerfile-Änderung. Der Backend startet Container direkt:
```python
docker.run(image="...", command="python sync.py --sync-delta")
```
**Skripte hinzugefügt oder geändert?** → Image neu bauen + pushen:
```bash
docker build -f service/scripts/jobs-image/Dockerfile -t docker.nes.uni-due.de/inse/background-jobs:latest .
docker push docker.nes.uni-due.de/inse/background-jobs:latest
```
Lokal testen ohne Pull:
```bash
export BACKGROUND_JOBS_PULL_BEFORE_RUN=false
```
## Scheduling
Job mit `schedule: "0 3 * * *"` und `enabled: true` läuft automatisch täglich um 3:00 UTC. Manuell starten: "Jetzt ausführen" Button oder API.
## Logs
Während Laufzeit: Live vom Container. Nach Beendigung: Letzte 200 Zeilen in der DB. Frontend: "Logs anzeigen" Button.
## Docker-Socket (Deployment)
```yaml
# docker-compose
backend:
volumes:
- /var/run/docker.sock:/var/run/docker.sock
```
Ohne Socket-Mount funktioniert nichts.
## Env-Variablen
Standard-Image erhält automatisch:
- `INSE_ELASTIC_URL`, `INSE_ELASTIC_API_KEY`
- `INSE_LLM_*`, `ELASTICSEARCH_INSE_*`, `SENTENCE_TRANSFORMERS_MODEL_NAME`
Plus `env` aus der Job-Definition.
**Eigene Images** bekommen nur die `env`-Variablen (Sicherheit).
## API
- `GET /api/background-jobs/tasks` — Jobs auflisten
- `POST /api/background-jobs/tasks` — Job anlegen
- `DELETE /api/background-jobs/tasks/{id}` — Job löschen
- `POST /api/background-jobs/tasks/{id}/run` — Run starten
- `PATCH /api/background-jobs/tasks/{id}` — Schedule ändern
- `GET /api/background-jobs/runs/{id}/logs` — Logs abrufen
- `POST /api/background-jobs/runs/{id}/stop` — Run stoppen
Alle Endpoints erfordern Superadmin-Auth.
+151
View File
@@ -0,0 +1,151 @@
import os
import requests
from requests.adapters import HTTPAdapter
from urllib.parse import quote
from dotenv import load_dotenv
load_dotenv()
INSE_URL = os.getenv("INSE_ELASTIC_URL", "https://inse.nes.uni-due.de/elastic")
INSE_API_KEY = os.getenv("INSE_ELASTIC_API_KEY")
if not INSE_API_KEY:
raise RuntimeError(
"INSE_ELASTIC_API_KEY is not set. Copy .env.example to .env and fill it in, "
"or pass it as an environment variable."
)
ES_HEADERS = {
"Authorization": f"ApiKey {INSE_API_KEY}",
"Content-Type": "application/json",
}
_session = requests.Session()
_session.headers.update(ES_HEADERS)
_adapter = HTTPAdapter(pool_connections=32, pool_maxsize=32)
_session.mount("https://", _adapter)
_session.mount("http://", _adapter)
def _send_es_request(method: str, url: str, payload: dict = None) -> dict:
try:
response = _session.request(
method=method,
url=url,
json=payload,
)
response.raise_for_status()
return response.json()
except requests.RequestException as error:
print(f"Send Request failed: ({method} {url}): {error}")
raise
def add_entry(index: str, entry: dict):
endpoint = f"{INSE_URL}/{index}/_doc"
document_body = {
"news_id": entry["news_id"],
"relevant": int(entry["relevant"]),
"authors": entry["authors"],
"keywords": entry.get("keywords", []),
}
response_data = _send_es_request("POST", endpoint, payload=document_body)
created_id = response_data["_id"]
entry["_id"] = created_id
return created_id
def index_entry(index: str, document_id: str, entry: dict):
encoded_document_id = quote(document_id, safe="")
endpoint = f"{INSE_URL}/{index}/_doc/{encoded_document_id}"
document_body = {
"news_id": entry["news_id"],
"relevant": int(entry["relevant"]),
"authors": entry["authors"],
"keywords": entry.get("keywords", []),
}
return _send_es_request("PUT", endpoint, payload=document_body)
def update_entry(index: str, document_id: str, partial_doc: dict):
encoded_document_id = quote(document_id, safe="")
endpoint = f"{INSE_URL}/{index}/_update/{encoded_document_id}"
return _send_es_request("POST", endpoint, payload={"doc": partial_doc})
def get_entry(index: str, document_id: str) -> dict:
encoded_document_id = quote(document_id, safe="")
endpoint = f"{INSE_URL}/{index}/_doc/{encoded_document_id}"
return _send_es_request("GET", endpoint)
def delete_entry(index: str, document_id: str):
encoded_document_id = quote(document_id, safe="")
endpoint = f"{INSE_URL}/{index}/_doc/{encoded_document_id}"
return _send_es_request("DELETE", endpoint)
def get_all_entries(index: str, fields: list = None) -> list:
if not fields:
source_fields = True
else:
source_fields = fields
endpoint = f"{INSE_URL}/{index}/_search"
page_size = 1000
results = []
last_sort_value = None
while True:
payload = {
"query": {"match_all": {}},
"size": page_size,
"sort": [{"_doc": "asc"}],
"_source": source_fields,
}
if last_sort_value is not None:
payload["search_after"] = last_sort_value
response_data = _send_es_request("POST", endpoint, payload=payload)
results_list = response_data["hits"]["hits"]
if not results_list:
break
results.extend(results_list)
last_sort_value = results_list[-1]["sort"]
return results
def delete_all_entries(index: str):
endpoint = f"{INSE_URL}/{index}/_delete_by_query"
payload = {
"query": {"match_all": {}}
}
return _send_es_request("POST", endpoint, payload=payload)
def remove_field_all(index: str, field: str):
endpoint = f"{INSE_URL}/{index}/_update_by_query"
payload = {
"query": {"exists": {"field": field}},
"script": {
"source": f"ctx._source.remove('{field}')",
"lang": "painless",
},
}
return _send_es_request("POST", endpoint, payload=payload)
+95
View File
@@ -0,0 +1,95 @@
import os
import requests
from openai import OpenAI, APIConnectionError
from dotenv import load_dotenv
load_dotenv()
LLM_BASE_URL = os.getenv("INSE_LLM_BASE_URL", "https://project.nes.uni-due.de/llm2/v1/")
LLM_API_KEY = os.getenv("INSE_LLM_API_KEY")
if not LLM_API_KEY:
raise RuntimeError(
"INSE_LLM_API_KEY is not set. Copy .env.example to .env and fill it in, "
"or pass it as an environment variable."
)
LLM_MODEL = os.getenv("INSE_LLM_MODEL", "gemma4-e4b")
SYSTEM_PROMPT_RELEVANT = ("""
Du bewertest Nachrichtenartikel aus dem Campus-Aktuell-Bereich der Universität Duisburg-Essen.
Entscheide, ob der Artikel inhaltlich über eine konkrete Person berichtet, also über deren Werdegang, Forschung, Leistung, Auszeichnung oder Tätigkeit.
Falls du dir unsicher bist, ob eine Person im Mittelpunkt steht, dann entscheide dich bitte für die positivere Option (also 1), damit die Namensextraktion auf keinen Fall bei Artikeln mit Personenbezug versäumt wird.
Antworte mit 1, wenn eine konkrete Person im Mittelpunkt steht.
Antworte mit 0, wenn es sich um allgemeine Mitteilungen handelt, die keine einzelne Person in den Mittelpunkt stellen, zum Beispiel Veranstaltungs- und Terminhinweise, Spendenaufrufe, organisatorische Ankündigungen, allgemeine Universitätsinformationen oder Pressemitteilungen ohne Personenbezug.
Die bloße Nennung von Namen (etwa als Autor oder Ansprechpartner) reicht für eine 1 nicht aus; die Person muss inhaltlich Thema des Artikels sein.
Antworte ausschließlich mit einer einzigen Ziffer: 0 oder 1.
""")
SYSTEM_PROMPT_NAMES = ("""
Aus dem nachfolgenden Campus-Aktuell-Artikel der Universität Duisburg-Essen: Nenne die Namen aller konkreten Personen, um die es im Artikel inhaltlich geht.
Es können mehrere Personen sein. Bitte achte darauf dass du nur die Namen der Personen nennst, die tatsächlich im Mittelpunkt des Artikels stehen.
Insbesondere am Ende von Artikeln werden oft Personen genannt, die nur als Ansprechpartner oder Organisator und sollen deshalb nicht genannt werden.
Antworte ausschließlich mit gültigem JSON in exakt diesem Format: {\"person\": [\"Vorname Nachname\", \"Vorname Nachname\"]}
Gib keine Erklärungen und kein Markdown aus, nur das JSON.
""")
SYSTEM_PROMPT_KEYWORDS = ("""
Extrahiere aus dem nachfolgenden Campus-Aktuell-Artikel der Universität Duisburg-Essen die wichtigsten Schlagwörter (Keywords).
Wähle ausschließlich Begriffe oder Phrasen, die tatsächlich im Text vorkommen. Erfinde keine Begriffe, verallgemeinere nicht und nenne keine Oberbegriffe, die nicht im Text stehen.
Übersetze keine Begriffe – verwende ausschließlich Wörter und Phrasen in der Sprache des Artikels.
Gib jedes Schlagwort in seiner Grundform an: Bei deutschen Begriffen Substantive im Nominativ Singular; bei englischen Begriffen Substantive im Singular. Verwende den Plural nur, wenn der Begriff üblicherweise im Plural gebraucht wird.
Vermeide Redundanz: Wenn zwei mögliche Schlagwörter dieselbe Wortbasis teilen (z.B. „Forschung" und „Forschungsprojekt"), nenne nur den spezifischeren Begriff.
Nenne maximal sechs prägnante Begriffe oder kurze Phrasen. Konzentriere dich auf inhaltlich zentrale Begriffe, nicht auf Personennamen oder Datumsangaben.
Antworte ausschließlich mit gültigem JSON in exakt diesem Format: {\"keywords\": [\"Schlagwort\", \"Schlagwort\"]}
Gib keine Erklärungen und kein Markdown aus, nur das JSON.
""")
_client = OpenAI(
base_url=LLM_BASE_URL,
api_key=LLM_API_KEY,
timeout=30,
)
def call(system_prompt, user_prompt, model=LLM_MODEL, temperature=1.0, top_p=0.95):
try:
response = _client.chat.completions.create(
model=model,
messages=[
{"role": "system", "content": system_prompt},
{"role": "user", "content": user_prompt},
],
temperature=temperature,
top_p=top_p,
extra_body={"top_k": 64},
)
except APIConnectionError:
return None
return response.choices[0].message.content or None
def is_news_relevant(text: str) -> bool:
result = call(SYSTEM_PROMPT_RELEVANT, text)
if result is None:
return False
return result.strip() == "1"
def extract_names(text: str) -> list[str]:
result = call(SYSTEM_PROMPT_NAMES, text)
if result is None:
return []
try:
import json
data = json.loads(result)
return data.get("person", [])
except json.JSONDecodeError:
return []
def extract_keywords(text: str) -> list[str]:
result = call(SYSTEM_PROMPT_KEYWORDS, text)
if result is None:
return []
try:
import json
data = json.loads(result)
return data.get("keywords", [])
except json.JSONDecodeError:
return []
+246
View File
@@ -0,0 +1,246 @@
import elastic.client as es_client
import llm.client as llm_client
import json
import argparse
import time
import logging
import threading
from concurrent.futures import ThreadPoolExecutor, as_completed
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logger = logging.getLogger(__name__)
POSTPROC_INDEX = "aktuell_postproc"
def print_pretty_json(data):
logger.info(json.dumps(data, indent=2))
def sync_single_news(news_id, max_retries=3):
attempt = 0
while attempt < max_retries:
try:
news_text = es_client.get_entry("aktuell", news_id)["_source"]["full_content"]
is_news_relevant = llm_client.is_news_relevant(news_text)
authors = llm_client.extract_names(news_text)
keywords = llm_client.extract_keywords(news_text)
new_entry = {
"news_id": news_id,
"relevant": is_news_relevant,
"authors": authors,
"keywords": keywords,
}
es_client.add_entry("aktuell_postproc", new_entry)
return True
except Exception as error:
attempt += 1
logger.warning(f"Warning syncing news_id {news_id} (Attempt {attempt}/{max_retries})")
if attempt < max_retries:
time.sleep(1)
else:
logger.error(f"Error: {news_id} - {error}")
return False
def update_keywords_single(postproc_entry, target_index=POSTPROC_INDEX, max_retries=3):
doc_id = postproc_entry["_id"]
source = postproc_entry["_source"]
news_id = source["news_id"]
attempt = 0
while attempt < max_retries:
try:
news_text = es_client.get_entry("aktuell", news_id)["_source"]["full_content"]
keywords = llm_client.extract_keywords(news_text)
if not keywords:
# Empty article or unparseable LLM answer: writing an empty list
# would look like a success and block a later retry.
logger.info(f"Skipped {news_id}: no keywords extracted.")
return False
if target_index == POSTPROC_INDEX:
es_client.update_entry(POSTPROC_INDEX, doc_id, {"keywords": keywords})
else:
# Key the target doc on news_id so re-runs update it in place
# instead of piling up a new document each time.
es_client.index_entry(
target_index,
news_id,
{
"news_id": news_id,
"relevant": source.get("relevant", 0),
"authors": source.get("authors", []),
"keywords": keywords,
},
)
return True
except Exception as error:
attempt += 1
logger.warning(f"Warning updating keywords for news_id {news_id} (Attempt {attempt}/{max_retries})")
if attempt < max_retries:
time.sleep(1)
else:
logger.error(f"Error: {news_id} - {error}")
return False
def main():
parser = argparse.ArgumentParser(description="Synchronize news articles from 'aktuell' index to 'aktuell_postproc' index with relevance and author extraction using LLM.")
parser.add_argument(
"--delete-all",
action="store_true",
help="Delete all entries from index 'aktuell_postproc'.",
)
parser.add_argument(
"--sync-delta",
action="store_true",
help="Sync only missing entries from 'aktuell' to 'aktuell_postproc'.",
)
parser.add_argument(
"--update-keywords",
action="store_true",
help="Add 'keywords' to existing 'aktuell_postproc' entries that don't have them yet (keeps relevant/authors).",
)
parser.add_argument(
"--reset-keywords",
action="store_true",
help="Remove the 'keywords' field from all 'aktuell_postproc' entries (keeps relevant/authors). Run before re-extracting with a new prompt.",
)
parser.add_argument(
"--stats",
action="store_true",
help="Print statistics about the entries in 'aktuell_postproc' and 'aktuell'.",
)
parser.add_argument(
"--threads",
type=int,
default=4,
help="Number of threads for --sync-delta (Default: 4).",
)
parser.add_argument(
"--limit",
type=int,
default=None,
help="Process at most this many entries (used by --update-keywords, e.g. for a smoke test).",
)
parser.add_argument(
"--target-index",
default=POSTPROC_INDEX,
help=(
f"Index that --update-keywords writes to (default: {POSTPROC_INDEX}). Any other "
"index gets new documents instead of in-place updates, and every entry is "
"re-extracted rather than only those missing keywords."
),
)
args = parser.parse_args()
if args.delete_all:
es_client.delete_all_entries("aktuell_postproc")
if args.reset_keywords:
result = es_client.remove_field_all("aktuell_postproc", "keywords")
logger.info(f"Removed 'keywords' from {result.get('updated', 0)} entries.")
if args.sync_delta:
start_time = time.time()
aktuell_ids_raw = es_client.get_all_entries("aktuell", fields=["_id"])
postproc_ids_raw = es_client.get_all_entries("aktuell_postproc", fields=["news_id"])
source_ids = set(entry["_id"] for entry in aktuell_ids_raw)
target_ids = set(entry["_source"]["news_id"] for entry in postproc_ids_raw)
missing_ids = source_ids - target_ids
logger.info(f"Number of missing IDs: {len(missing_ids)}")
missing_ids = list(missing_ids)
total = len(missing_ids)
processed = 0
succeeded = 0
progress_lock = threading.Lock()
with ThreadPoolExecutor(max_workers=args.threads) as executor:
futures = [executor.submit(sync_single_news, news_id) for news_id in missing_ids]
for future in as_completed(futures):
was_successful = future.result()
with progress_lock:
processed += 1
if was_successful:
succeeded += 1
logger.info(f"Sync: {processed} / {total}")
end_time = time.time()
logger.info(f"Sync DONE: {succeeded} entries synced.")
logger.info(f"Time taken: {end_time - start_time} seconds.")
if args.update_keywords:
start_time = time.time()
postproc_entries = es_client.get_all_entries(
POSTPROC_INDEX, fields=["news_id", "keywords", "relevant", "authors"]
)
if args.target_index == POSTPROC_INDEX:
pending = [entry for entry in postproc_entries if not entry["_source"].get("keywords")]
logger.info(f"Number of entries without keywords: {len(pending)}")
else:
# Writing elsewhere never marks the postproc entries, so the "missing
# keywords" filter would select the same entries on every run. Pick
# entries that already have keywords instead: those are known to come
# from articles with actual content, unlike the empty archive stubs.
pending = [entry for entry in postproc_entries if entry["_source"].get("keywords")]
logger.info(f"Re-extracting keywords into '{args.target_index}': {len(pending)} candidates.")
if args.limit is not None:
pending = pending[:args.limit]
total = len(pending)
logger.info(f"Processing {total} entries.")
processed = 0
succeeded = 0
progress_lock = threading.Lock()
with ThreadPoolExecutor(max_workers=args.threads) as executor:
futures = [
executor.submit(update_keywords_single, entry, args.target_index)
for entry in pending
]
for future in as_completed(futures):
was_successful = future.result()
with progress_lock:
processed += 1
if was_successful:
succeeded += 1
logger.info(f"Update keywords: {processed} / {total}")
end_time = time.time()
logger.info(f"Update keywords DONE: {succeeded} entries updated.")
logger.info(f"Time taken: {end_time - start_time} seconds.")
if args.stats:
aktuell_entries = es_client.get_all_entries("aktuell", fields=["_id"])
logger.info(f"Total entries in 'aktuell': {len(aktuell_entries)}")
postproc_entries = es_client.get_all_entries("aktuell_postproc", fields=["_id", "news_id", "relevant", "authors", "keywords"])
total_entries = len(postproc_entries)
relevant_count = sum(1 for entry in postproc_entries if entry["_source"]["relevant"] == 1)
irrelevant_count = total_entries - relevant_count
news_with_extracted_names = sum(1 for entry in postproc_entries if entry["_source"]["authors"])
news_without_extracted_names = total_entries - news_with_extracted_names
news_with_keywords = sum(1 for entry in postproc_entries if entry["_source"].get("keywords"))
news_without_keywords = total_entries - news_with_keywords
logger.info(f"Total entries in 'aktuell_postproc': {total_entries}")
logger.info(f"Relevant entries: {relevant_count}")
logger.info(f"Irrelevant entries: {irrelevant_count}")
logger.info(f"Entries with extracted names: {news_with_extracted_names}")
logger.info(f"Entries without extracted names: {news_without_extracted_names}")
logger.info(f"Entries with keywords: {news_with_keywords}")
logger.info(f"Entries without keywords: {news_without_keywords}")
if __name__ == "__main__":
main()
@@ -15,10 +15,11 @@ The objective is to measure match coverage and determine which ID-matching strat
Source: `cordis_eu_fp7_project_iprs` Source: `cordis_eu_fp7_project_iprs`
Patents tested: 5196(total) - 2270(others) -> 2926 (EP and US patents) Patents tested: 5196(total) - 2270(others) -> 2926 (EP and US patents)
| Prefix | Count |
| Prefix | Count |
| --------- | --------: | | --------- | --------: |
| EP | 1,952 | | EP | 1,952 |
| US | 974 | | US | 974 |
| **Total** | **2,926** | | **Total** | **2,926** |
## Matching Strategies ## Matching Strategies
+3 -1
View File
@@ -20,7 +20,9 @@ RUN pip install --root-user-action=ignore --no-cache-dir --disable-pip-version-c
"sqlmodel~=0.0.33" \ "sqlmodel~=0.0.33" \
"argon2-cffi~=25.1.0" \ "argon2-cffi~=25.1.0" \
"pandas~=2.3.3" \ "pandas~=2.3.3" \
"pypdf==6.14.2" "pypdf==6.14.2"\
"docker~=7.1.0" \
"croniter~=6.0.0"
COPY [ "src/main", "/home" ] COPY [ "src/main", "/home" ]
COPY [ "src/data", "/data" ] COPY [ "src/data", "/data" ]
+1 -1
View File
@@ -61,7 +61,7 @@ task exportOpenApiSpec(type: Exec) {
task runServeContainer(type: Exec) { task runServeContainer(type: Exec) {
dependsOn createImage dependsOn createImage
commandLine 'docker', 'run', '--rm', '-v', "${projectDir}/src/main:/home", '-v', "${projectDir}/src/data:/data", '-p', '8000:8000', '-e', "DOCKER_DEFAULT_PLATFORM='${targetPlatform}'", '-e', "INSE_AUTH_STANDALONE=true", '-e', 'INSE_OPENALEX_WORKS_API_KEY', '--name', "${imageName}-service-serve", '--detach', "${imagePrefix}-service:${imageVersion}", 'run', '--reload', '--reload-dir', './inse' commandLine 'docker', 'run', '--rm', '-v', "${projectDir}/src/main:/home", '-v', "${projectDir}/src/data:/data", '-v', '/var/run/docker.sock:/var/run/docker.sock', '-p', '8000:8000', '-e', "DOCKER_DEFAULT_PLATFORM='${targetPlatform}'", '-e', "INSE_AUTH_STANDALONE=true", '-e', 'INSE_OPENALEX_WORKS_API_KEY', '--name', "${imageName}-service-serve", '--detach', "${imagePrefix}-service:${imageVersion}", 'run', '--reload', '--reload-dir', './inse'
} }
task stopServeContainer(type: Exec) { task stopServeContainer(type: Exec) {
+20
View File
@@ -0,0 +1,20 @@
import sys
import time
import logging
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logger = logging.getLogger(__name__)
def main() -> None:
seconds = int(sys.argv[1]) if len(sys.argv) > 1 else 20
logger.info(f"Demo job started, running for {seconds} seconds.")
for elapsed in range(1, seconds + 1):
time.sleep(1)
if elapsed % 5 == 0:
logger.info(f"Progress: {elapsed}/{seconds} seconds.")
logger.info("Demo job finished successfully.")
if __name__ == "__main__":
main()
+21
View File
@@ -0,0 +1,21 @@
# Background-jobs worker image. Build from the repo root:
# docker build -f service/scripts/jobs-image/Dockerfile -t docker.nes.uni-due.de/inse/background-jobs:latest .
FROM python:3.13-slim
WORKDIR /app
# Headless Chrome for the bund foerderportal crawler (Selenium).
RUN apt-get update \
&& apt-get install -y --no-install-recommends chromium chromium-driver \
&& rm -rf /var/lib/apt/lists/*
ENV CHROME_BIN=/usr/bin/chromium \
CHROMEDRIVER_PATH=/usr/bin/chromedriver
# Install dependencies
COPY service/scripts/jobs-image/requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Copy the job code.
COPY background-jobs/app/ ./
COPY service/scripts/ ./service/scripts/
+137
View File
@@ -0,0 +1,137 @@
# Job Images
## Anlegen und Bearbeiten eines Jobs (UI)
Ein Job im Frontend ist nur eine **Definition** in der Datenbank, die auf ein
Image zeigt. Der eigentliche Job-Code steckt im Image. Reihenfolge daher immer:
**erst das Image nach Nexus pushen, dann den Job in der UI anlegen.**
### 1. Image bauen und pushen
Aus dem Repo-Root (Build-Kontext = Root), Beispiel News-Crawler (jedes
Dockerfile nennt in seinem Kopf den eigenen Build-Befehl):
```bash
docker build -f service/scripts/jobs-image/news-crawl/Dockerfile \
-t docker.nes.uni-due.de/inse/jobs/news-crawl:latest .
docker push docker.nes.uni-due.de/inse/jobs/news-crawl:latest
```
Login zu Nexus vorher, falls nötig: `docker login docker.nes.uni-due.de`
(Zugangsdaten wie in der Backend-`.env`, `BACKGROUND_JOBS_REGISTRY_*`).
Erst wenn Push erfolgreich war, taucht das Image in der Image-Auswahl der UI auf.
### 2. Job anlegen
1. Als **Superadmin** anmelden und die Seite **Jobs** öffnen.
2. Oben rechts prüfen, dass die Karten **Docker-Daemon** und **Nexus-Registry**
grün („Erreichbar") sind. Ist Nexus rot, bleibt die Image-Auswahl leer —
dann Registry/`.env` prüfen, bevor es weitergeht.
3. Auf **Neuer Job** klicken. Im Dialog:
- **Name** – Pflichtfeld, muss eindeutig sein (sonst 409).
- **Beschreibung**, **Ziel-Index** – optional, nur zur Anzeige.
- **Image** – Pflichtfeld. In das Feld tippen und aus der
Nexus-Autovervollständigung den passenden Tag wählen, z. B.
`docker.nes.uni-due.de/inse/jobs/news-crawl:latest`. Leer = Fehler.
- **Befehl** – optional. Wird an den `ENTRYPOINT` des Images **angehängt**
(z. B. `--max-items 50`). Leer lassen, wenn die Image-Defaults reichen.
- **Umgebungsvariablen** – optional, `KEY=VALUE` pro Zeile. Bei
Nexus-Images werden die INSE-Zugangsdaten (Elasticsearch/LLM) ohnehin
automatisch ergänzt; hier nur Zusätzliches/Overrides.
4. **Speichern**. Der Job erscheint in der Tabelle, zunächst ohne Zeitplan
(= nur manuell).
### 3. Job ausführen und beobachten
- **▶ Jetzt ausführen** startet einen Lauf. Das Backend pullt das Image und
startet einen Container namens `<job-slug>-run-<id>`.
- **⏹ Stoppen** bricht einen laufenden Lauf ab.
- **🗎 Logs** zeigt die Container-Logs (live während des Laufs, danach die in der
DB gespeicherten letzten Zeilen) sowie Dauer bzw. „läuft seit".
- Schlägt der Pull fehl (Image gelöscht/nicht gepusht), wird der Lauf
**fehlgeschlagen** mit `failed to pull image …` im Log — dann Image neu pushen.
### 4. Job bearbeiten
- In der **Name**-Spalte erscheint beim Hovern ein **Stift**-Symbol → öffnet den
Bearbeiten-Dialog. Dort lassen sich **Name, Beschreibung, Ziel-Index, Image,
Befehl und Env** ändern (gleiche Validierung wie beim Anlegen).
- Das **Kalender**-Symbol in der Aktionsspalte öffnet den **Zeitplan**-Dialog:
Cron-Ausdruck setzen (5 Felder) und Job aktiv/inaktiv schalten. Ein Zeitplan
macht aus einem manuellen Job einen automatisch laufenden.
- Bearbeiten ist gesperrt, solange ein Lauf des Jobs läuft.
### 5. Job löschen
Das **Papierkorb**-Symbol entfernt die Job-Definition. Das Image in Nexus bleibt
davon unberührt (siehe unten zum Image-Löschen).
One Docker image per job script. Each image installs only its own dependencies
and bakes its script as the `ENTRYPOINT`. Most jobs then run with no `command`
override — the job definition just points `image` at the matching tag. Where
several jobs share one script (the demos), they point at the same image and
differ only by their `command`.
## Images
| Job (DB name) | Image | Entrypoint | Notes |
| ----------------------- | --------------------- | ---------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| News-Crawler | `jobs/news-crawl` | `run_pipeline.py` | scrapy<2.13, Twisted<24.7; uploads to `NEWS_UPLOAD_INDEX` |
| Bund-Crawler | `jobs/bund-crawl` | `gpc.data.py --max-rows 200` | headless Chrome; uploads to `BUND_UPLOAD_INDEX`; capped, full export is ~300k rows |
| Project-Topic-Mapping | `jobs/project-topics` | `map_project_topics --output-index docker-job_test` | reads projects_bund_v1; needs host backend |
| News-Topic-Mapping | `jobs/news-topics` | `map_news_topics --output-index aktuell_openalex_topics` | bundles both topic_mapper pkgs; needs host backend |
| News-Keyword-Extraction | `jobs/news-keywords` | `sync.py --update-keywords --target-index docker-job_test` | ES + LLM creds; writes to test index |
| Demo-Job A / B / C | `jobs/demo` | `demo.py` (seconds via command: `20` / `25` / `30`) | no dependencies; one image, three job rows |
Each image is its own repository under the `jobs/` path namespace, prefixed
`docker.nes.uni-due.de/inse/` (e.g. `docker.nes.uni-due.de/inse/jobs/news-crawl:latest`).
The three demo jobs share the single `jobs/demo` repository.
The entrypoints carry no run limits: anything set in the job's `command` field is
appended to the entrypoint, so limits (`--max-items`, `--max-docs`, `--limit`) are
passed per run from the UI. The one exception is the Bund-Crawler, which keeps a
`--max-rows` cap in the image because its full export is ~300k rows.
## Build
From the repo root (the build context must be the repo root so the Dockerfiles
can copy `service/scripts/…` and `background-jobs/app/`):
```bash
docker build -f service/scripts/jobs-image/news-crawl/Dockerfile \
-t docker.nes.uni-due.de/inse/jobs/news-crawl:latest .
docker push docker.nes.uni-due.de/inse/jobs/news-crawl:latest
```
Each image's Dockerfile header lists its own build command.
## Running locally without pushing
Before each run the backend pulls the job's image from the registry when it is a
registry image (host `docker.nes.uni-due.de`). **There is no fallback to a local
copy:** if the pull fails, the run is marked _failed_ and the error is written to
the run log — a stale local image is never used silently. To run a locally built
image without pushing it, skip the pull attempt entirely:
```bash
export BACKGROUND_JOBS_PULL_BEFORE_RUN=false
```
With the pull disabled the backend uses whatever image with that tag exists on
the Docker host, so `docker build -t docker.nes.uni-due.de/inse/jobs/<name>:latest .`
is enough for local runs.
## Env vars
Because every tag lives under the `docker.nes.uni-due.de` registry host, the
backend treats these as registry images and injects the INSE Elasticsearch / LLM
credentials automatically (plus any per-job `env`).
Most images write to the test index by default: the crawlers upload into the
index named by `NEWS_UPLOAD_INDEX` / `BUND_UPLOAD_INDEX` (both baked to
`docker-job_test` in their Dockerfile), and the project mapper and the keyword
extraction write to `docker-job_test` via `--output-index` / `--target-index`.
The exception is News-Topic-Mapping, which writes to `aktuell_openalex_topics`.
To not contact Elasticsearch at all, pass `--skip-upload` (crawlers) or
`--dry-run` (mappers) through the job's command field.
@@ -0,0 +1,28 @@
# Bund-Crawler (foerderportal export via headless Chrome). Build from the repo root:
# docker build -f service/scripts/jobs-image/bund-crawl/Dockerfile -t docker.nes.uni-due.de/inse/jobs/bund-crawl:latest .
FROM python:3.13-slim
WORKDIR /app
ENV PYTHONUNBUFFERED=1
# Upload the crawled projects into the shared test index (gpc.data.py reads
# ELASTICSEARCH_INSE_* creds + BUND_UPLOAD_INDEX from the env).
ENV BUND_UPLOAD_INDEX=docker-job_test
# Headless Chrome for the Selenium crawler.
RUN apt-get update \
&& apt-get install -y --no-install-recommends chromium chromium-driver \
&& rm -rf /var/lib/apt/lists/*
ENV CHROME_BIN=/usr/bin/chromium \
CHROMEDRIVER_PATH=/usr/bin/chromedriver
COPY service/scripts/jobs-image/bund-crawl/requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY service/scripts/projects/bund/ ./service/scripts/projects/bund/
WORKDIR /app/service/scripts/projects/bund
# Capped on purpose: the full export is ~300k rows, so an uncapped run would
# write that entire volume into BUND_UPLOAD_INDEX. Raise or drop the cap by
# passing --max-rows N through the job's command field.
ENTRYPOINT ["python", "gpc.data.py", "--max-rows", "200"]
@@ -0,0 +1,3 @@
selenium~=4.20
pandas~=2.2
requests~=2.32
@@ -0,0 +1,21 @@
# News-Crawler (UDE 'aktuell'). Build from the repo root:
# docker build -f service/scripts/jobs-image/news-crawl/Dockerfile -t docker.nes.uni-due.de/inse/jobs/news-crawl:latest .
#
# scrapy<2.13 + Twisted<24.7 are load-bearing: the spiders use the removed
# start_requests() hook, and newer versions silently crawl 0 items.
FROM python:3.13-slim
WORKDIR /app
ENV PYTHONUNBUFFERED=1
# Upload the crawled articles into the shared test index (see upload_aktuell.py,
# which reads ELASTICSEARCH_INSE_* creds + NEWS_UPLOAD_INDEX from the env).
ENV NEWS_UPLOAD_INDEX=docker-job_test
COPY service/scripts/jobs-image/news-crawl/requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY service/scripts/news/ude/ ./service/scripts/news/ude/
# Uncapped: crawls every article and uploads to NEWS_UPLOAD_INDEX. Limit a run by
# passing --max-items N through the job's command field.
ENTRYPOINT ["python", "service/scripts/news/ude/run_pipeline.py"]
@@ -0,0 +1,3 @@
scrapy>=2.11,<2.13
Twisted>=22.10,<24.7
requests~=2.32
@@ -0,0 +1,21 @@
# News keyword extraction (LLM keyword extraction into docker-job_test).
# Build from the repo root:
# docker build -f service/scripts/jobs-image/news-keywords/Dockerfile -t docker.nes.uni-due.de/inse/jobs/news-keywords:latest .
#
# Needs Elasticsearch + LLM creds (injected as env vars by the backend for
# registry images). Calls the LLM once per entry.
FROM python:3.13-slim
WORKDIR /app
ENV PYTHONUNBUFFERED=1
COPY service/scripts/jobs-image/news-keywords/requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY background-jobs/app/ ./
# Writes into docker-job_test, leaving production aktuell_postproc untouched.
# A non-postproc target re-extracts entries that already have keywords (real
# content) and updates them in place, keyed on news_id (re-runs overwrite, no
# duplicates). Cap a run by appending --limit N via the job's command field.
ENTRYPOINT ["python", "sync.py", "--update-keywords", "--target-index", "docker-job_test"]
@@ -0,0 +1,3 @@
requests~=2.32
openai~=2.41
python-dotenv~=1.0
@@ -0,0 +1,24 @@
# News-Topic-Mapping (news keywords -> OpenAlex topics). Build from the repo root:
# docker build -f service/scripts/jobs-image/news-topics/Dockerfile -t docker.nes.uni-due.de/inse/jobs/news-topics:latest .
#
# map_news_topics imports map_project_topics as its "base", so both topic_mapper
# packages must be present. Needs a reachable backend and Elasticsearch creds
# (injected as env vars by the backend for registry images).
FROM python:3.13-slim
WORKDIR /app
ENV PYTHONUNBUFFERED=1
COPY service/scripts/jobs-image/news-topics/requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY service/scripts/news/topic_mapper/ ./service/scripts/news/topic_mapper/
COPY service/scripts/projects/topic_mapper/ ./service/scripts/projects/topic_mapper/
# Writes topic mappings into aktuell_openalex_topics. Only maps (article, keyword)
# pairs not already present in the output index; pass --overwrite to re-map all.
# Uncapped: limit a run by passing --max-docs N through the job's command field.
# host.docker.internal reaches the host backend for vector search.
ENTRYPOINT ["python", "-m", "service.scripts.news.topic_mapper.map_news_topics", \
"--output-index", "aktuell_openalex_topics", \
"--api-base-url", "http://host.docker.internal:8000"]
@@ -0,0 +1,2 @@
httpx>=0.27
python-dotenv>=1.0
@@ -0,0 +1,25 @@
# Projekt-Topic-Mapping (bund keywords -> OpenAlex topics). Build from the repo root:
# docker build -f service/scripts/jobs-image/project-topics/Dockerfile -t docker.nes.uni-due.de/inse/jobs/project-topics:latest .
#
# Needs a reachable backend (vector search) and Elasticsearch creds. The creds
# arrive as env vars injected by the backend for registry images.
FROM python:3.13-slim
WORKDIR /app
ENV PYTHONUNBUFFERED=1
COPY service/scripts/jobs-image/project-topics/requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY service/scripts/projects/topic_mapper/ ./service/scripts/projects/topic_mapper/
# Writes topic mappings into docker-job_test. Only maps (project, keyword) pairs
# not already present in the output index, so an interrupted run can be resumed.
# There is no overwrite flag: to re-map all, point --output-index at a fresh index.
# Uncapped: limit a run by passing --max-docs N through the job's command field.
# host.docker.internal reaches the host backend for vector search.
ENTRYPOINT ["python", "-m", "service.scripts.projects.topic_mapper.map_project_topics", \
"--source-index", "projects_bund_v1", \
"--text-field", "Leistungsplansystematik_fullname", \
"--output-index", "docker-job_test", \
"--api-base-url", "http://host.docker.internal:8000"]
@@ -0,0 +1,2 @@
httpx>=0.27
python-dotenv>=1.0
@@ -0,0 +1,9 @@
requests~=2.32
openai~=2.41
python-dotenv~=1.0
scrapy>=2.11,<2.13
Twisted>=22.10,<24.7
httpx~=0.27
selenium~=4.20
pandas~=2.2
elasticsearch>=7.17,<8
@@ -0,0 +1,80 @@
# News → OpenAlex topic mapping
Batch counterpart to `news.logic._match_topics_for_keywords`, which matches an
article's keywords on every detail request without persisting the result. This
script maps the LLM-extracted `keywords` of the enriched articles in
`aktuell_postproc` to OpenAlex topics via the backend's
`/api/topics/vector-search` endpoint, and persists one document per
(article, keyword) pair into an output index with the explicit mapping from
`news_mapping.py`:
```json
{
"news_id": "...",
"keyword": "<one of the article's keywords>",
"source_index": "aktuell_postproc",
"source_field": "keywords",
"topic_matches": [
{
"rank": 1,
"topic_id": "...",
"topic_display_name": "...",
"subfield": "...",
"field": "...",
"domain": "...",
"match_score": null
}
],
"match_method": "sentence_transformer",
"model_name": "...",
"built_at": "..."
}
```
`match_score` is `null` because the endpoint does not expose Elasticsearch
scores; `rank` preserves the search result order.
This script only ever **reads** `aktuell_postproc` and writes into the separate test index. Caching the topics back into `aktuell_postproc` is done by the news detail endpoint (`news/logic.py`), not here.
Keywords are **not** extracted here. `background-jobs/app/sync.py` (job `news`)
writes them into `aktuell_postproc` first, the same way the bund projects
already carry their keyword field before `map_project_topics.py` runs.
The Elasticsearch plumbing (point-in-time scan, batched topic search, bulk
indexing, retries) is imported from
`service/scripts/projects/topic_mapper/map_project_topics.py` rather than
duplicated — that directory must stay next to this one.
## Setup
```bash
pip install -r requirements.txt
```
Credentials are read from `service/src/main/inse/.env` by default (override
with `--env-file`), and the backend must be running (e.g. `./gradlew serve`)
because the topic search goes through its API.
## Usage
```bash
python map_news_topics.py --output-index docker-job_test
```
Test run against a few articles without writing anything:
```bash
python map_news_topics.py --output-index docker-job_test --dry-run --max-docs 50
```
Runs are resumable: (article, keyword) pairs already present in the output
index are skipped, and each unique keyword is searched only once across all
articles that use it. Pairs whose search failed are left unwritten so the next
run retries them.
## As a background job
Packaged as the `news-topics` registry image (see
`service/scripts/jobs-image/news-topics/Dockerfile`), writing into
`aktuell_openalex_topics`. The run is uncapped; limit a run by passing
`--max-docs N` through the job's command field.
@@ -0,0 +1,329 @@
#!/usr/bin/env python3
"""
map_news_topics.py — Map news keywords to OpenAlex topics.
Batch counterpart to news.logic._match_topics_for_keywords. This script streams
the enriched articles from aktuell_postproc, reads their LLM-extracted
'keywords', matches every unique keyword against OpenAlex topics and persists
one document per (article, keyword) pair into a separate output index:
{news_id, keyword, source_index, source_field, topic_matches[],
match_method, model_name, built_at}
The source index is only ever read. Writing the topics back into
aktuell_postproc is the job of the news detail endpoint, not of this script.
Keywords are not extracted here — sync.py (job 'news') writes them into
aktuell_postproc, the same way the bund projects already carry their keyword
field before map_project_topics.py runs.
The run is resumable: (article, keyword) pairs already present in the output
index are skipped, so an interrupted run can simply be restarted. Each unique
keyword is searched only once, across all articles that use it.
Usage:
python map_news_topics.py --output-index docker-job_test
Requires ELASTICSEARCH_INSE_URL/ELASTICSEARCH_INSE_API_KEY in the environment
or in the service .env, plus a running backend serving
/api/topics/vector-search (e.g. ./gradlew serve).
"""
from __future__ import annotations
import argparse
import asyncio
import hashlib
import json
import logging
import os
import sys
from datetime import datetime, timezone
from pathlib import Path
from dotenv import load_dotenv
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "projects" / "topic_mapper"))
import map_project_topics as base
sys.path.insert(0, str(Path(__file__).resolve().parent))
from news_mapping import NEWS_TOPICS_MAPPING
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logger = logging.getLogger(__name__)
SOURCE_INDEX = "aktuell_postproc"
KEYWORD_FIELD = "keywords"
NEWS_ID_FIELD = "news_id"
async def ensure_index(index: str, cluster: str) -> None:
"""Creates the output index with the explicit mapping if it does not exist."""
url, headers = base.es_headers(cluster)
client = base.get_http_client()
response = await client.head(f"{url}/{index}", headers=headers)
if response.status_code == 200:
logger.info("Output index '%s' already exists.", index)
return
response = await client.put(
f"{url}/{index}", json={"mappings": NEWS_TOPICS_MAPPING}, headers=headers
)
response.raise_for_status()
logger.info("Created output index '%s' with explicit mapping.", index)
def output_doc_id(news_id: str, keyword: str) -> str:
"""Stable id per (article, keyword) pair.
Derived from news_id rather than the aktuell_postproc document id, so a
reindex of the postproc index does not duplicate the mappings.
"""
digest = hashlib.sha1(keyword.encode("utf-8")).hexdigest()[:12]
return f"{news_id}::{digest}"
async def fetch_source_entries(cluster: str, max_docs: int | None) -> dict[str, tuple[str, str]]:
"""Returns output_doc_id -> (news_id, keyword) for every enriched article."""
entries: dict[str, tuple[str, str]] = {}
total = 0
docs_with_keywords = 0
async for hit in base.scan(
index=SOURCE_INDEX,
cluster=cluster,
query={"exists": {"field": KEYWORD_FIELD}},
source=[NEWS_ID_FIELD, KEYWORD_FIELD],
):
total += 1
doc_source = hit.get("_source", {})
keywords = base.extract_text_values(doc_source, KEYWORD_FIELD)
news_id = doc_source.get(NEWS_ID_FIELD)
if keywords and news_id:
docs_with_keywords += 1
for keyword in keywords:
entries[output_doc_id(news_id, keyword)] = (news_id, keyword)
if total % 50000 == 0:
logger.info("Scanned %d source documents...", total)
if max_docs and total >= max_docs:
logger.info("Stopping scan at --max-docs=%d.", max_docs)
break
logger.info(
"Scanned %d documents from '%s', %d with non-empty '%s' (%d article/keyword pairs).",
total,
SOURCE_INDEX,
docs_with_keywords,
KEYWORD_FIELD,
len(entries),
)
return entries
async def run(args: argparse.Namespace) -> None:
built_at = datetime.now(timezone.utc).isoformat()
model_name = os.getenv("SENTENCE_TRANSFORMERS_MODEL_NAME")
await base.check_backend(args.api_base_url)
if not args.dry_run:
await ensure_index(index=args.output_index, cluster=args.output_cluster)
entries = await fetch_source_entries(cluster=args.source_cluster, max_docs=args.max_docs)
if not entries:
logger.warning("No keywords in '%s' — run the 'news' job first.", SOURCE_INDEX)
return
if args.overwrite:
logger.info("--overwrite: re-mapping every pair, existing documents are replaced.")
covered = set()
else:
covered = await base.fetch_covered_doc_ids(
index=args.output_index, cluster=args.output_cluster
)
pending = {doc_id: entry for doc_id, entry in entries.items() if doc_id not in covered}
logger.info(
"Coverage: %d/%d pairs already in '%s', %d still to be processed.",
len(entries) - len(pending),
len(entries),
args.output_index,
len(pending),
)
if not pending:
logger.info("Nothing left to process.")
return
docs_by_keyword: dict[str, list[tuple[str, str]]] = {}
for doc_id, (news_id, keyword) in pending.items():
docs_by_keyword.setdefault(keyword, []).append((doc_id, news_id))
unique_keywords = sorted(docs_by_keyword)
logger.info(
"%d unique keywords cover the %d pending pairs.", len(unique_keywords), len(pending)
)
backup_docs: list[dict] = []
docs_done = 0
keywords_done = 0
for start in range(0, len(unique_keywords), args.text_batch_size):
chunk = unique_keywords[start : start + args.text_batch_size]
matches_by_keyword = await base.match_keywords(
chunk,
api_base_url=args.api_base_url,
top_k=args.top_k,
search_type=args.search_type,
)
documents = []
for keyword in chunk:
if keyword not in matches_by_keyword:
continue # search failed — left for the next run
for doc_id, news_id in docs_by_keyword[keyword]:
documents.append(
(
doc_id,
{
"news_id": news_id,
"keyword": keyword,
"source_index": SOURCE_INDEX,
"source_field": KEYWORD_FIELD,
"topic_matches": matches_by_keyword[keyword],
"match_method": base.MATCH_METHOD,
"model_name": model_name,
"built_at": built_at,
},
)
)
if documents and not args.dry_run:
await base.bulk_index(
index=args.output_index, cluster=args.output_cluster, documents=documents
)
if args.output:
backup_docs.extend(doc for _, doc in documents)
keywords_done += len(chunk)
docs_done += len(documents)
logger.info(
"Progress: %d/%d keywords, %d/%d pending pairs indexed into '%s'.",
keywords_done,
len(unique_keywords),
docs_done,
len(pending),
args.output_index,
)
skipped = len(pending) - docs_done
if skipped:
logger.warning(
"%d pairs were NOT indexed due to failed searches — rerun the script to retry.",
skipped,
)
if args.output:
output_path = Path(args.output)
output_path.parent.mkdir(parents=True, exist_ok=True)
output_path.write_text(
json.dumps(backup_docs, indent=2, ensure_ascii=False), encoding="utf-8"
)
logger.info("Wrote local JSON backup (%d documents) to %s", len(backup_docs), output_path)
logger.info(
"Done. %d documents indexed this run, %d covered in total.",
docs_done,
len(covered) + docs_done,
)
def main() -> None:
parser = argparse.ArgumentParser(
description="Map the keywords of enriched news articles to OpenAlex topics.",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=(
"Examples:\n"
" python map_news_topics.py --output-index docker-job_test\n"
" python map_news_topics.py --output-index docker-job_test --dry-run --max-docs 50"
),
)
parser.add_argument(
"--output-index", required=True, help="Index to persist the topic mappings into"
)
parser.add_argument(
"--source-cluster",
default="inse",
choices=["inse", "nes"],
help=f"Cluster holding '{SOURCE_INDEX}' (default: inse)",
)
parser.add_argument(
"--output-cluster",
default="inse",
choices=["inse", "nes"],
help="Cluster of the output index (default: inse)",
)
parser.add_argument(
"--api-base-url",
default=base.DEFAULT_API_BASE_URL,
help=f"Base URL of the running backend (default: {base.DEFAULT_API_BASE_URL})",
)
parser.add_argument(
"--top-k",
type=int,
default=1,
help=(
"Number of topic matches per keyword (default: 1, matching the single "
"match the news detail endpoint shows). Only truncates the result list; "
"ranking is unaffected."
),
)
parser.add_argument(
"--search-type",
default="hybrid",
choices=["hybrid", "semantic"],
help="Topic search type, mirrors vector_search_topics (default: hybrid)",
)
parser.add_argument(
"--text-batch-size",
type=int,
default=base.TEXT_BATCH_SIZE,
help=f"Unique keywords searched per chunk (default: {base.TEXT_BATCH_SIZE})",
)
parser.add_argument(
"--env-file",
default=str(base.DEFAULT_ENV_FILE),
help=f"Path to a .env with Elasticsearch credentials (default: {base.DEFAULT_ENV_FILE})",
)
parser.add_argument(
"--max-docs",
type=int,
default=None,
help=f"Stop scanning '{SOURCE_INDEX}' after N documents (for test runs)",
)
parser.add_argument(
"--output",
default=None,
help="Optional path for a local JSON backup of the documents built this run",
)
parser.add_argument(
"--overwrite",
action="store_true",
help=(
"Re-map pairs that are already in the output index instead of skipping "
"them; document ids are deterministic, so they are replaced in place "
"(use after changing --top-k or --search-type)"
),
)
parser.add_argument(
"--dry-run",
action="store_true",
help="Build the mapping without creating/writing the output index",
)
args = parser.parse_args()
if args.env_file and Path(args.env_file).exists():
load_dotenv(dotenv_path=args.env_file)
asyncio.run(run(args))
if __name__ == "__main__":
main()
@@ -0,0 +1,30 @@
"""Elasticsearch mapping for news -> OpenAlex topic mapping indices.
One document per (news article, keyword) pair. Articles in aktuell_postproc
carry up to KEYWORD_LIMIT keywords each, so an article normally yields
several documents.
"""
NEWS_TOPICS_MAPPING = {
"properties": {
"news_id": {"type": "keyword"},
"keyword": {"type": "text", "fields": {"keyword": {"type": "keyword"}}},
"source_index": {"type": "keyword"},
"source_field": {"type": "keyword"},
"topic_matches": {
"type": "nested",
"properties": {
"rank": {"type": "integer"},
"topic_id": {"type": "keyword"},
"topic_display_name": {"type": "keyword"},
"subfield": {"type": "keyword"},
"field": {"type": "keyword"},
"domain": {"type": "keyword"},
"match_score": {"type": "float"},
},
},
"match_method": {"type": "keyword"},
"model_name": {"type": "keyword"},
"built_at": {"type": "date"},
}
}
@@ -0,0 +1,2 @@
httpx>=0.27
python-dotenv>=1.0
+40 -10
View File
@@ -3,6 +3,12 @@ import sys
import os import os
import shutil import shutil
import time import time
import argparse
import logging
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logger = logging.getLogger(__name__)
def run_command(command, cwd=None): def run_command(command, cwd=None):
"""Run a shell command and exit if it fails.""" """Run a shell command and exit if it fails."""
@@ -12,11 +18,27 @@ def run_command(command, cwd=None):
#capture_output=True, #supresses output from subprocess #capture_output=True, #supresses output from subprocess
text=True) text=True)
if result.returncode != 0: if result.returncode != 0:
print(f"Command failed: {command}") logger.error(f"Command failed: {command}")
print("Error output:\n", result.stderr) logger.error(f"Error output:\n{result.stderr}")
sys.exit(result.returncode) sys.exit(result.returncode)
if __name__ == "__main__": if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="Crawl the UDE 'aktuell' news pages and upload the articles to Elasticsearch."
)
parser.add_argument(
"--skip-upload",
action="store_true",
help="Only crawl into out/*.json and never connect to Elasticsearch",
)
parser.add_argument(
"--max-items",
type=int,
default=None,
help="Stop each spider after N items (for short test runs)",
)
args = parser.parse_args()
start_time = time.time() start_time = time.time()
base_dir = os.path.dirname(os.path.abspath(__file__)) base_dir = os.path.dirname(os.path.abspath(__file__))
@@ -31,19 +53,27 @@ if __name__ == "__main__":
output_file_meta = os.path.join(out_dir, "meta.json") output_file_meta = os.path.join(out_dir, "meta.json")
print("Running Scrapy link crawler...") limit = f" -s CLOSESPIDER_ITEMCOUNT={args.max_items}" if args.max_items else ""
run_command(f"scrapy crawl aktuell-links -O \"{output_file_links}\"", cwd=crawler_dir)
print("Running Scrapy meta crawler...") logger.info("Running Scrapy link crawler...")
run_command(f"scrapy crawl aktuell-metadata -O \"{output_file_meta}\"", cwd=crawler_dir) run_command(f"scrapy crawl aktuell-links -O \"{output_file_links}\"{limit}", cwd=crawler_dir)
print("Running upload script") logger.info("Running Scrapy meta crawler...")
run_command(f"{sys.executable} upload_aktuell.py {output_file_meta}", cwd=base_dir) run_command(f"scrapy crawl aktuell-metadata -O \"{output_file_meta}\"{limit}", cwd=crawler_dir)
if args.skip_upload:
logger.info("Skipping upload (--skip-upload): Elasticsearch was not contacted.")
else:
logger.info("Running upload script")
run_command(f"{sys.executable} upload_aktuell.py {output_file_meta}", cwd=base_dir)
end_time = time.time() end_time = time.time()
runtime_seconds = end_time - start_time runtime_seconds = end_time - start_time
runtime_hours = runtime_seconds / 3600 runtime_hours = runtime_seconds / 3600
print(f"Runtime: {runtime_hours:.2f} hours") logger.info(f"Runtime: {runtime_hours:.2f} hours")
print("Finished crawling and uploading UDE news articles.") if args.skip_upload:
logger.info("Finished crawling UDE news articles (no upload).")
else:
logger.info("Finished crawling and uploading UDE news articles.")
+33 -221
View File
@@ -1,231 +1,39 @@
from elasticsearch import Elasticsearch
import sys import sys
import os import os
import json import json
from datetime import datetime
import time import time
import logging
from urllib.parse import quote
# elasticsearch-connection should be adjusted import requests
# uni-server
es = Elasticsearch()
index_name = "aktuell-test" #test indices to make sure everything works before uploading to the real index, ps. you lack rights to push to the real index, please contact the admin if you want to push to the real index logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logger = logging.getLogger(__name__)
# The INSE key is index-scoped and can't hit cluster endpoints (e.g. GET /), so
# the elasticsearch client's ping/product-check would 403. We talk to the index
# endpoint directly over HTTP with the ApiKey header, like the other jobs do.
ES_URL = os.getenv("ELASTICSEARCH_INSE_URL", "http://localhost:9200").rstrip("/")
ES_API_KEY = os.getenv("ELASTICSEARCH_INSE_API_KEY")
# Default is a test index — you lack rights to push to the production index;
# contact the ES admin for that. Override via NEWS_UPLOAD_INDEX.
# The target index is never created here: an index that doesn't exist yet gets
# ES dynamic mapping, without the searchabilityAnalyzer the search relies on.
# Create it with the proper mapping before pointing a run at a new index.
INDEX_NAME = os.getenv("NEWS_UPLOAD_INDEX", "aktuell-test")
# checks if elastic is up and creates the index if not already done _session = requests.Session()
def check_elastic(): _session.headers.update({"Content-Type": "application/json"})
if not es.ping(): if ES_API_KEY:
sys.exit("No connection to Elasticsearch") _session.headers.update({"Authorization": f"ApiKey {ES_API_KEY}"})
if not es.indices.exists(index=index_name):
settings = {
"analysis": {
"analyzer": {
"searchabilityAnalyzer": {
"type": "custom",
"tokenizer": "standard",
"filter": [
"lowercase",
"asciifolding"
]
}
}
}
}
mappings = {
"properties": {
"subtitle": {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"maintitle": {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"author": {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"date": {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"date_year": {
"type": "long",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"date_full": {
"type": "long",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"intro_content": {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"main_content": {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"further_content": {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"redaktion": {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"full_content": {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"tags": {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
},
"tags_nested": {
"type": "nested",
"properties": {
"tag": {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 250
}
}
}
}
},
#"links": {
# "type": "text",
# "analyzer": "searchabilityAnalyzer",
# "search_analyzer": "searchabilityAnalyzer",
# "fields": {
# "keyword": {
# "type": "keyword",
# "ignore_above": 256
# }
# }
#},
"links_nested": {
"type": "nested",
"properties": {
"url": {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 250
}
}
},
"text": {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 250
}
}
}
}
},
}
}
es.indices.create(index=index_name, mappings=mappings, settings=settings)
def upload(path): def upload(path):
with open(path, "r", encoding='utf-8') as json_file: with open(path, "r", encoding="utf-8") as json_file:
try: try:
json_loaded = json.load(json_file) json_loaded = json.load(json_file)
uploaded = 0
for news in json_loaded: for news in json_loaded:
time.sleep(10 / 1000) time.sleep(10 / 1000)
id = (str(news["date"]) + "_" + str(news["author"]) + "_" + str(news["maintitle"])).replace(" ", "").replace("/", "").replace("ö", "").replace("ä", "").replace("ü", "").replace("Ö", "").replace("Ä", "").replace("Ü", "").replace(".", "").replace("?", "") id = (str(news["date"]) + "_" + str(news["author"]) + "_" + str(news["maintitle"])).replace(" ", "").replace("/", "").replace("ö", "").replace("ä", "").replace("ü", "").replace("Ö", "").replace("Ä", "").replace("Ü", "").replace(".", "").replace("?", "")
@@ -241,7 +49,7 @@ def upload(path):
for p in range(len(tags)): for p in range(len(tags)):
tags_nested.append({"tag": tags[p]}) tags_nested.append({"tag": tags[p]})
dict = { document = {
"subtitle": news["subtitle"], "subtitle": news["subtitle"],
"maintitle": news["maintitle"], "maintitle": news["maintitle"],
"tags": news["tags"], "tags": news["tags"],
@@ -255,21 +63,25 @@ def upload(path):
"tags_nested": tags_nested, "tags_nested": tags_nested,
"date_year": news["date_year"], "date_year": news["date_year"],
"date_full": news["date_full"], "date_full": news["date_full"],
#"links": news["links"],
"links_nested": links_nested, "links_nested": links_nested,
"url": news["url"] "url": news["url"]
} }
es.index(index=index_name, id=id, document=dict) response = _session.put(
f"{ES_URL}/{INDEX_NAME}/_doc/{quote(id, safe='')}",
json=document,
)
response.raise_for_status()
uploaded += 1
logger.info(f"Uploaded {uploaded} news articles to '{INDEX_NAME}'.")
except Exception as e: except Exception as e:
print("--- Failed to upload news.") logger.error(f"Failed to upload news: {e}")
print(e)
# main - entry point # main - entry point
if __name__ == '__main__': if __name__ == '__main__':
check_elastic()
if len(sys.argv) != 2: if len(sys.argv) != 2:
sys.exit("No path given.") sys.exit("No path given.")
upload(sys.argv[1]) upload(sys.argv[1])
+99 -117
View File
@@ -12,14 +12,34 @@ import pandas as pd
import json import json
from datetime import datetime from datetime import datetime
import sys import sys
from elasticsearch import Elasticsearch, helpers
from elasticsearch.helpers import bulk,BulkIndexError
import os import os
import math
import requests
import hashlib import hashlib
import argparse
import logging
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
logger = logging.getLogger(__name__)
download_path=os.path.abspath(os.getcwd()) download_path=os.path.abspath(os.getcwd())
es = Elasticsearch()
# The INSE key is index-scoped and can't hit cluster endpoints (e.g. GET /), so
# the elasticsearch client's ping/product-check would 403. We POST to _bulk
# directly over HTTP with the ApiKey header, like the other jobs do.
ES_URL = os.getenv("ELASTICSEARCH_INSE_URL", "http://localhost:9200").rstrip("/")
ES_API_KEY = os.getenv("ELASTICSEARCH_INSE_API_KEY")
# Default is a test index — you lack rights to push to the production index;
# contact the ES admin for that. Override via BUND_UPLOAD_INDEX.
# The target index is never created here: an index that doesn't exist yet gets
# ES dynamic mapping, without the searchabilityAnalyzer the search relies on.
# Create it with the proper mapping before pointing a run at a new index.
INDEX_NAME = os.getenv("BUND_UPLOAD_INDEX", "projects_bund_test")
_session = requests.Session()
if ES_API_KEY:
_session.headers.update({"Authorization": f"ApiKey {ES_API_KEY}"})
def crawl_data(link,driver): def crawl_data(link,driver):
driver.get(link) driver.get(link)
@@ -41,123 +61,61 @@ def crawl_data(link,driver):
time.sleep(2) time.sleep(2)
# Switch to the alert and Clicks the "OK" button # Switch to the alert and Clicks the "OK" button
Alert(driver).accept() Alert(driver).accept()
print("downloading data") logger.info("downloading data")
else: else:
# The element is likely a honeypot, do not interact # The element is likely a honeypot, do not interact
print("Honeypot detected, skipping interaction") logger.info("Honeypot detected, skipping interaction")
def check_elastic_online():
if not es.ping():
sys.exit("No connection to Elasticsearch")
else :
print("Elasticsearch connection established")
def check_elastic_index(df, index_name): def _clean(value):
# pandas/numpy scalars -> native python; NaN -> None (ES rejects NaN in JSON).
if hasattr(value, "item"):
value = value.item()
if isinstance(value, float) and math.isnan(value):
return None
return value
if not es.indices.exists(index=index_name):
print(index_name + " index wasn't found. Creating a new one..")
settings = {
"analysis": {
"analyzer": {
"searchabilityAnalyzer": {
"type": "custom",
"tokenizer": "standard",
"filter": [
"lowercase",
"asciifolding"
]
}
}
}
}
mappings = {}
properties = {}
for key in list(df.columns): def upload_data(df, index_name):
if key in ("funding_start", "funding_end", "datum"): logger.info("Uploading data...")
properties[key] = {
"type": "date",
"format": "dd.MM.yyyy"
}
elif key == "Publikationsdatum":
properties[key] = {
"type": "date",
"format": "yyyy"
}
elif key == "unix_timestamp":
properties[key] = {
"type": "long"
}
elif key == "Fördersumme":
properties[key] = {
"type": "float"
}
elif key == "new":
properties[key] = {
"type": "boolean"
}
else:
properties[key] = {
"type": "text",
"analyzer": "searchabilityAnalyzer",
"search_analyzer": "searchabilityAnalyzer",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
mappings["properties"] = properties docs = []
for _, row in df.iterrows():
es.indices.create(index=index_name, mappings=mappings, settings=settings)
es.indices.refresh(index=index_name)
print("The new index '"+index_name+"' has been created")
else:
print(index_name + " already exists. Uploading data...")
def upload_data(df,index_name):
def fill_docs_to_upload(row):
doc_id = hashlib.sha256(str(row['Förderkennzeichen']).encode('utf-8')).hexdigest() doc_id = hashlib.sha256(str(row['Förderkennzeichen']).encode('utf-8')).hexdigest()
doc = { source = {key: _clean(val) for key, val in row.to_dict().items()}
"_op_type": "update", # Update existing documents source["new"] = True
"_index": index_name, docs.append((doc_id, source))
"_id": doc_id,
"doc": {
"new":False
},
"upsert":{
**row.to_dict(),
"new":True
}
}
docs_to_upload.append(doc)
print("Uploading data...")
try:
check_elastic_index(df, index_name)
except Exception as e:
print("Error while creating index")
print(e)
docs_to_upload = []
df.apply(fill_docs_to_upload,axis=1)
def bulk_docs(docs,data_rate):
response_sum = 0
for i in range(0, len(docs), data_rate):
try:
response = helpers.bulk(es,docs[i:i + data_rate])
response_sum = response_sum + response[0]
except BulkIndexError as e:
print(f"{len(e.errors)} document(s) failed to index.")
for error in e.errors:
print("Error details:", error)
print ("Upload is completed. "+ str(response_sum) +" documents have been uploaded." )
data_rate = 200 data_rate = 200
bulk_docs(docs_to_upload,data_rate) uploaded = 0
for i in range(0, len(docs), data_rate):
batch = docs[i:i + data_rate]
lines = []
for doc_id, source in batch:
# update + upsert: flag an existing project as not-new, or create an
# unseen one from the row (with new=True).
lines.append(json.dumps({"update": {"_index": index_name, "_id": doc_id}}))
lines.append(json.dumps({"doc": {"new": False}, "upsert": source}, default=str))
payload = ("\n".join(lines) + "\n").encode("utf-8")
response = _session.post(
f"{ES_URL}/_bulk",
data=payload,
headers={"Content-Type": "application/x-ndjson"},
)
response.raise_for_status()
result = response.json()
if result.get("errors"):
failed = [item for item in result["items"]
if next(iter(item.values())).get("status", 200) >= 300]
logger.error(f"{len(failed)} document(s) failed to index.")
for item in failed[:5]:
logger.error(f"Error details: {item}")
uploaded += len(batch) - len(failed)
else:
uploaded += len(batch)
logger.info(f"Upload is completed. {uploaded} documents have been uploaded to '{index_name}'.")
@@ -170,7 +128,7 @@ def wait_for_file_complete(download_path,file_name):
fname.endswith(".part") or fname.endswith(".crdownload") fname.endswith(".part") or fname.endswith(".crdownload")
for fname in os.listdir(download_path) for fname in os.listdir(download_path)
): ):
print(f"Download complete: {file_name}") logger.info(f"Download complete: {file_name}")
return True return True
if any(fname.endswith((".part", ".crdownload")) for fname in os.listdir(download_path)): if any(fname.endswith((".part", ".crdownload")) for fname in os.listdir(download_path)):
time.sleep(1) time.sleep(1)
@@ -180,7 +138,7 @@ def wait_for_file_complete(download_path,file_name):
def format_data(df): def format_data(df):
print("Formattind data...") logger.info("Formatting data...")
df.drop(list(df.filter(regex='.1|Unnamed')), axis=1, inplace=True) df.drop(list(df.filter(regex='.1|Unnamed')), axis=1, inplace=True)
def clean_format(text): def clean_format(text):
if isinstance(text, str): if isinstance(text, str):
@@ -233,7 +191,10 @@ def setup_chrome_driver(download_path):
"download.directory_upgrade": True, "download.directory_upgrade": True,
"plugins.always_open_pdf_externally": True, "plugins.always_open_pdf_externally": True,
}) })
chromedriver_path = "/home/inse/miniconda3/envs/airflow/bin/chromedriver" chrome_bin = os.getenv("CHROME_BIN")
if chrome_bin:
options.binary_location = chrome_bin
chromedriver_path = os.getenv("CHROMEDRIVER_PATH", "/usr/bin/chromedriver")
service = Service(executable_path=chromedriver_path) service = Service(executable_path=chromedriver_path)
driver = webdriver.Chrome(service=service, options=options) driver = webdriver.Chrome(service=service, options=options)
return driver return driver
@@ -241,7 +202,23 @@ def setup_chrome_driver(download_path):
# main - entry point # main - entry point
if __name__ == '__main__': if __name__ == '__main__':
print("Starting") parser = argparse.ArgumentParser(
description="Crawl the bund foerderportal project export and upload it to Elasticsearch."
)
parser.add_argument(
"--skip-upload",
action="store_true",
help="Only crawl and format the export; never connect to Elasticsearch",
)
parser.add_argument(
"--max-rows",
type=int,
default=None,
help="Keep at most this many rows of the formatted export (e.g. for a smoke test).",
)
args = parser.parse_args()
logger.info("Starting")
file_path = os.path.join(os.path.abspath(os.getcwd()), 'Suchliste.csv') file_path = os.path.join(os.path.abspath(os.getcwd()), 'Suchliste.csv')
if not os.path.exists(file_path): if not os.path.exists(file_path):
driver = setup_chrome_driver(download_path) driver = setup_chrome_driver(download_path)
@@ -255,8 +232,13 @@ if __name__ == '__main__':
df = pd.DataFrame(file) df = pd.DataFrame(file)
df_formatted = format_data(df) df_formatted = format_data(df)
index_name = "projects_bund_test" #test indices to make sure everything works before uploading to the real index, ps. you lack rights to push to the real index, please contact the admin if you want to push to the real index if args.max_rows:
check_elastic_online() df_formatted = df_formatted.head(args.max_rows)
upload_data(df_formatted,index_name)
os.remove(file_path) if args.skip_upload:
logger.info(f"Skipping upload (--skip-upload): Elasticsearch was not contacted. "
f"Formatted {len(df_formatted)} rows.")
else:
upload_data(df_formatted, INDEX_NAME)
os.remove(file_path)
+4
View File
@@ -17,3 +17,7 @@ SENTENCE_TRANSFORMERS_MODEL_NAME=intfloat/multilingual-e5-base
TOKEN_ISSUER_ID=inse TOKEN_ISSUER_ID=inse
TOKEN_HMAC_KEY=9dd09c80dd0796fa24bd2007f4cf57fc28c9a38909b7e83bb2d73121c5bc69c7 TOKEN_HMAC_KEY=9dd09c80dd0796fa24bd2007f4cf57fc28c9a38909b7e83bb2d73121c5bc69c7
# Docker-Registry-Login für Background-Jobs (Nexus, nes.uni-due.de)
BACKGROUND_JOBS_REGISTRY_USERNAME=student
BACKGROUND_JOBS_REGISTRY_PASSWORD=nes-student!
@@ -0,0 +1,146 @@
"""
Database tables and API schemas for the background job runner.
"""
from datetime import datetime, timezone
from enum import StrEnum
from typing import Optional
from pydantic import BaseModel
from sqlmodel import JSON, Column, Field, SQLModel
class JobRunStatus(StrEnum):
RUNNING = "running"
SUCCEEDED = "succeeded"
FAILED = "failed"
STOPPED = "stopped"
class JobTriggeredBy(StrEnum):
SCHEDULE = "schedule"
MANUAL = "manual"
def utcnow() -> datetime:
return datetime.now(timezone.utc).replace(tzinfo=None)
class JobDefinition(SQLModel, table=True):
__tablename__ = "background_job_definition"
id: Optional[int] = Field(default=None, primary_key=True)
name: str = Field(
index=True, unique=True, description="Human-readable job name shown in the UI."
)
description: str = Field(default="", description="What this job does.")
target_index: str = Field(
default="", description="Elasticsearch index the job writes to (UI info)."
)
image: Optional[str] = Field(
default=None,
description="Docker image to run. Null falls back to the configured "
"background-jobs image.",
)
command: Optional[str] = Field(
default=None,
description="Command passed to the image. Null uses the job name (for "
"known jobs) or the image's default entrypoint.",
)
env: dict[str, str] = Field(
default_factory=dict,
sa_column=Column(JSON),
description="Extra environment variables passed to the container.",
)
schedule: Optional[str] = Field(
default=None,
description="Cron expression in UTC (e.g. '0 3 * * *'). Null = manual only.",
)
enabled: bool = Field(
default=True, description="Disabled definitions are never scheduled."
)
next_run_at: Optional[datetime] = Field(
default=None, description="Computed by the scheduler from the cron expression."
)
created_at: datetime = Field(default_factory=utcnow)
class JobRun(SQLModel, table=True):
__tablename__ = "background_job_run"
id: Optional[int] = Field(default=None, primary_key=True)
definition_id: int = Field(
foreign_key="background_job_definition.id", index=True
)
container_id: Optional[str] = Field(default=None)
status: JobRunStatus = Field(default=JobRunStatus.RUNNING)
triggered_by: JobTriggeredBy = Field(
description="Whether the scheduler or a superadmin started this run."
)
started_at: datetime = Field(default_factory=utcnow)
finished_at: Optional[datetime] = Field(default=None)
exit_code: Optional[int] = Field(default=None)
logs: Optional[str] = Field(
default=None,
description="Captured stdout/stderr, filled in when the run finishes "
"(the container itself is removed afterwards).",
)
class JobDefinitionCreateRequest(BaseModel):
name: str
image: Optional[str] = None
command: Optional[str] = None
env: dict[str, str] = {}
description: str = ""
target_index: str = ""
schedule: Optional[str] = None
enabled: bool = True
class JobDefinitionUpdateRequest(BaseModel):
name: Optional[str] = None
image: Optional[str] = None
command: Optional[str] = None
env: Optional[dict[str, str]] = None
description: Optional[str] = None
target_index: Optional[str] = None
schedule: Optional[str] = None
enabled: Optional[bool] = None
class BackgroundJobTask(BaseModel):
id: int
name: str
description: str
target_index: str
image: Optional[str]
command: Optional[str]
env: dict[str, str]
schedule: Optional[str]
enabled: bool
next_run_at: Optional[datetime]
last_run: Optional[JobRun]
status: str
class JobRunLogs(BaseModel):
run_id: int
status: JobRunStatus
logs: str
class DockerHealth(BaseModel):
reachable: bool
detail: str
class RegistryHealth(BaseModel):
reachable: bool
detail: str
host: str
class AvailableImages(BaseModel):
images: list[str]
detail: str = ""
@@ -0,0 +1,161 @@
from fastapi import APIRouter, Depends, Query, Response, status
from sqlmodel import Session
from inse.auth import service as auth_service
from inse.auth.model import AccessTokenMetadata
from inse.database import get_session
from inse.tags import Tags
from . import service
from .model import (
AvailableImages,
BackgroundJobTask,
DockerHealth,
RegistryHealth,
JobDefinitionCreateRequest,
JobDefinitionUpdateRequest,
JobRun,
JobRunLogs,
)
router = APIRouter(prefix="/api/background-jobs", tags=[Tags.BACKGROUND_JOBS])
@router.get(
"/tasks",
operation_id="getBackgroundJobTasks",
response_model=list[BackgroundJobTask],
)
async def get_tasks(
session: Session = Depends(get_session),
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> list[BackgroundJobTask]:
return service.get_tasks(session, access_token)
@router.post(
"/tasks",
operation_id="createBackgroundJobTask",
response_model=BackgroundJobTask,
status_code=status.HTTP_201_CREATED,
)
async def create_task(
payload: JobDefinitionCreateRequest,
session: Session = Depends(get_session),
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> BackgroundJobTask:
return service.create_task(session, access_token, payload)
@router.delete(
"/tasks/{task_id}",
operation_id="deleteBackgroundJobTask",
status_code=status.HTTP_204_NO_CONTENT,
)
async def delete_task(
task_id: int,
session: Session = Depends(get_session),
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> Response:
service.delete_task(session, access_token, task_id)
return Response(status_code=status.HTTP_204_NO_CONTENT)
@router.patch(
"/tasks/{task_id}",
operation_id="updateBackgroundJobTask",
response_model=BackgroundJobTask,
)
async def update_task(
task_id: int,
payload: JobDefinitionUpdateRequest,
session: Session = Depends(get_session),
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> BackgroundJobTask:
return service.update_task(session, access_token, task_id, payload)
@router.post(
"/tasks/{task_id}/run",
operation_id="runBackgroundJobTask",
response_model=JobRun,
)
async def run_task(
task_id: int,
session: Session = Depends(get_session),
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> JobRun:
return service.trigger_run(session, access_token, task_id)
@router.get(
"/tasks/{task_id}/runs",
operation_id="getBackgroundJobTaskRuns",
response_model=list[JobRun],
)
async def get_task_runs(
task_id: int,
limit: int = Query(default=20, ge=1, le=100),
session: Session = Depends(get_session),
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> list[JobRun]:
return service.get_task_runs(session, access_token, task_id, limit)
@router.get(
"/runs/{run_id}/logs",
operation_id="getBackgroundJobRunLogs",
response_model=JobRunLogs,
)
async def get_run_logs(
run_id: int,
session: Session = Depends(get_session),
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> JobRunLogs:
return service.get_run_logs(session, access_token, run_id)
@router.post(
"/runs/{run_id}/stop",
operation_id="stopBackgroundJobRun",
response_model=JobRun,
)
async def stop_run(
run_id: int,
session: Session = Depends(get_session),
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> JobRun:
return service.stop_run(session, access_token, run_id)
@router.get(
"/available-images",
operation_id="getBackgroundJobAvailableImages",
response_model=AvailableImages,
)
async def get_available_images(
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> AvailableImages:
return service.get_available_images(access_token)
@router.get(
"/docker-health",
operation_id="getBackgroundJobsDockerHealth",
response_model=DockerHealth,
)
async def docker_health(
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> DockerHealth:
return service.docker_health(access_token)
@router.get(
"/registry-health",
operation_id="getBackgroundJobsRegistryHealth",
response_model=RegistryHealth,
)
async def registry_health(
access_token: AccessTokenMetadata = auth_service.CurrentUserAccessTokenPayloadDep,
) -> RegistryHealth:
return service.registry_health(access_token)
@@ -0,0 +1,376 @@
"""
Launches background job containers via the host's Docker daemon and runs the
periodic schedule/reconcile loop.
"""
import asyncio
import logging
import re
from datetime import datetime
from threading import RLock
from typing import Optional
import docker
import httpx
from croniter import croniter
from docker.errors import NotFound
from sqlalchemy import update as sa_update
from sqlmodel import Session, select
from inse import config
from inse.database import engine
from .model import JobDefinition, JobRun, JobRunStatus, JobTriggeredBy, utcnow
logger = logging.getLogger(__name__)
settings = config.get_settings()
RUN_STATE_LOCK = RLock()
_client: Optional[docker.DockerClient] = None
def get_docker_client() -> docker.DockerClient:
global _client
if _client is None:
_client = docker.from_env()
return _client
def docker_reachable() -> tuple[bool, str]:
try:
get_docker_client().ping()
return True, "ok"
except Exception as error: # noqa: BLE001
return False, str(error)
def registry_reachable() -> tuple[bool, str]:
username = settings.background_jobs_registry_username
password = settings.background_jobs_registry_password
auth = (username, password) if username and password else None
host = registry_host()
try:
with httpx.Client(timeout=8.0, auth=auth) as client:
response = client.get(f"https://{host}/v2/")
if response.status_code == 200:
return True, "ok"
if response.status_code == 401:
return False, "authentication failed (401)"
return False, f"unexpected status {response.status_code}"
except Exception as error: # noqa: BLE001
return False, str(error)
def compute_next_run(schedule: str) -> datetime:
return croniter(schedule, utcnow()).get_next(datetime)
def job_environment() -> dict[str, str]:
environment = {
"INSE_ELASTIC_URL": settings.elasticsearch_inse_url,
"INSE_ELASTIC_API_KEY": settings.elasticsearch_inse_api_key,
"INSE_LLM_BASE_URL": settings.llm_api_url,
"INSE_LLM_API_KEY": settings.llm_api_key,
"INSE_LLM_MODEL": settings.llm_model,
"ELASTICSEARCH_INSE_URL": settings.elasticsearch_inse_url,
"ELASTICSEARCH_INSE_API_KEY": settings.elasticsearch_inse_api_key,
"SENTENCE_TRANSFORMERS_MODEL_NAME": settings.sentence_transformers_model_name,
}
return {key: value for key, value in environment.items() if value}
def registry_host() -> str:
return settings.background_jobs_image.split("/", 1)[0]
REGISTRY_IMAGE_LIMIT = 500
def list_registry_images() -> tuple[list[str], str]:
username = settings.background_jobs_registry_username
password = settings.background_jobs_registry_password
if not username or not password:
return [], "registry credentials are not configured"
host = registry_host()
base = f"https://{host}"
try:
with httpx.Client(timeout=10.0, auth=(username, password)) as client:
catalog = client.get(
f"{base}/v2/_catalog", params={"n": REGISTRY_IMAGE_LIMIT}
)
catalog.raise_for_status()
repositories = catalog.json().get("repositories", []) or []
images: list[str] = []
for repository in repositories:
try:
response = client.get(f"{base}/v2/{repository}/tags/list")
response.raise_for_status()
tags = response.json().get("tags") or []
except Exception: # noqa: BLE001
tags = []
if tags:
images.extend(f"{host}/{repository}:{tag}" for tag in tags)
else:
images.append(f"{host}/{repository}")
return sorted(images), ""
except Exception as error: # noqa: BLE001
logger.warning("Could not list registry images.", exc_info=True)
return [], str(error)
def resolve_image(definition: JobDefinition) -> Optional[str]:
return definition.image or None
def is_registry_image(image: Optional[str]) -> bool:
return bool(image) and image.split("/", 1)[0] == registry_host()
def container_name(definition: JobDefinition, run: JobRun) -> str:
slug = definition.name.lower()
slug = (
slug.replace("ä", "ae")
.replace("ö", "oe")
.replace("ü", "ue")
.replace("ß", "ss")
)
slug = re.sub(r"[^a-z0-9]+", "-", slug).strip("-")[:40].strip("-")
return f"{slug or 'job'}-run-{run.id}"
def resolve_command(definition: JobDefinition):
return definition.command or None
def resolve_environment(definition: JobDefinition) -> dict[str, str]:
base = job_environment() if is_registry_image(resolve_image(definition)) else {}
return {**base, **(definition.env or {})}
def registry_auth() -> Optional[dict[str, str]]:
if (
settings.background_jobs_registry_username
and settings.background_jobs_registry_password
):
return {
"username": settings.background_jobs_registry_username,
"password": settings.background_jobs_registry_password,
}
return None
def pull_image(image: str) -> None:
get_docker_client().images.pull(image, auth_config=registry_auth())
logger.info("Pulled image '%s' from the registry.", image)
def start_run(
session: Session, definition: JobDefinition, triggered_by: JobTriggeredBy
) -> JobRun:
run = JobRun(definition_id=definition.id, triggered_by=triggered_by)
session.add(run)
session.commit()
session.refresh(run)
image = resolve_image(definition)
if not image:
run.status = JobRunStatus.FAILED
run.finished_at = utcnow()
run.logs = "[system] No image configured for this job."
session.add(run)
session.commit()
session.refresh(run)
return run
if settings.background_jobs_pull_before_run and is_registry_image(image):
try:
pull_image(image)
except Exception as error: # noqa: BLE001
run.status = JobRunStatus.FAILED
run.finished_at = utcnow()
run.logs = (
f"[system] Failed to pull image '{image}' from the registry.\n"
f"[system] {error}"
)
session.add(run)
session.commit()
session.refresh(run)
return run
try:
container = get_docker_client().containers.run(
image=image,
command=resolve_command(definition),
environment=resolve_environment(definition),
detach=True,
name=container_name(definition, run),
remove=False,
)
run.container_id = container.id
except Exception as error: # noqa: BLE001
run.status = JobRunStatus.FAILED
run.finished_at = utcnow()
run.logs = (
f"[system] Failed to start the container for image '{image}'.\n"
f"[system] {error}"
)
session.add(run)
session.commit()
session.refresh(run)
return run
def has_running_run(session: Session, definition_id: int) -> bool:
return (
session.exec(
select(JobRun).where(
JobRun.definition_id == definition_id,
JobRun.status == JobRunStatus.RUNNING,
)
).first()
is not None
)
def schedule_due_jobs(session: Session) -> None:
now = utcnow()
scheduled = session.exec(
select(JobDefinition).where(
JobDefinition.enabled == True, # noqa: E712
JobDefinition.schedule != None, # noqa: E711
)
).all()
for definition in scheduled:
if definition.next_run_at is None:
definition.next_run_at = compute_next_run(definition.schedule)
session.add(definition)
continue
if definition.next_run_at > now:
continue
if has_running_run(session, definition.id):
logger.info(
"Skipping '%s': previous run still running.", definition.name
)
else:
run = start_run(session, definition, JobTriggeredBy.SCHEDULE)
logger.info(
"Started scheduled run %s of '%s'.", run.id, definition.name
)
definition.next_run_at = compute_next_run(definition.schedule)
session.add(definition)
session.commit()
def finalize_run(
session: Session,
run: JobRun,
*,
new_status: JobRunStatus,
expected_status: JobRunStatus = JobRunStatus.RUNNING,
exit_code: Optional[int] = None,
logs: Optional[str] = None,
) -> bool:
values: dict = {"status": new_status, "finished_at": utcnow()}
if exit_code is not None:
values["exit_code"] = exit_code
if logs is not None:
values["logs"] = logs
result = session.execute(
sa_update(JobRun)
.where(JobRun.id == run.id, JobRun.status == expected_status)
.values(**values)
)
return result.rowcount > 0
def append_system_log(logs: str, message: str) -> str:
base = logs.rstrip()
return f"{base}\n[system] {message}" if base else f"[system] {message}"
def remove_container(container, run_id: int) -> None:
try:
container.remove()
except Exception: # noqa: BLE001
logger.warning(
"Could not remove container for run %s.", run_id, exc_info=True
)
def reconcile_runs(session: Session) -> None:
with RUN_STATE_LOCK:
_reconcile_runs(session)
def _reconcile_runs(session: Session) -> None:
running = session.exec(
select(JobRun).where(JobRun.status == JobRunStatus.RUNNING)
).all()
for run in running:
if not run.container_id:
continue
try:
container = get_docker_client().containers.get(run.container_id)
except NotFound:
applied = finalize_run(
session,
run,
new_status=JobRunStatus.FAILED,
logs=(run.logs or "")
+ "\n[container disappeared before reconciliation]",
)
if applied:
session.commit()
logger.info(
"Run %s finished: failed (container disappeared).", run.id
)
continue
container.reload()
if container.status in ("exited", "dead"):
exit_code = container.attrs["State"]["ExitCode"]
new_status = (
JobRunStatus.SUCCEEDED if exit_code == 0 else JobRunStatus.FAILED
)
applied = finalize_run(
session,
run,
new_status=new_status,
exit_code=exit_code,
logs=container.logs().decode("utf-8", errors="replace"),
)
if applied:
session.commit()
remove_container(container, run.id)
logger.info(
"Run %s finished: %s (exit %s).", run.id, new_status, exit_code
)
session.commit()
def tick() -> None:
with Session(engine) as session:
schedule_due_jobs(session)
reconcile_runs(session)
async def scheduler_loop() -> None:
logger.info(
"Background job scheduler started (tick every %ss).",
settings.background_jobs_tick_seconds,
)
while True:
try:
await asyncio.to_thread(tick)
except Exception: # noqa: BLE001
logger.exception("Background job scheduler tick failed.")
await asyncio.sleep(settings.background_jobs_tick_seconds)
@@ -0,0 +1,401 @@
"""
Business logic for the superadmin-only background job endpoints.
"""
import logging
from croniter import croniter
from docker.errors import APIError, NotFound
from fastapi import HTTPException, status
from sqlmodel import Session, col, select
from inse import config
from inse.auth.model import AccessTokenMetadata, UserRole
from . import runner
from .model import (
AvailableImages,
BackgroundJobTask,
DockerHealth,
RegistryHealth,
JobDefinition,
JobDefinitionCreateRequest,
JobDefinitionUpdateRequest,
JobRun,
JobRunLogs,
JobRunStatus,
JobTriggeredBy,
utcnow,
)
logger = logging.getLogger(__name__)
settings = config.get_settings()
def _require_super_admin(access_token: AccessTokenMetadata) -> None:
if access_token.effective_role != UserRole.SUPER_ADMIN:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Only superadmins can manage background jobs.",
)
def _get_definition(session: Session, definition_id: int) -> JobDefinition:
definition = session.get(JobDefinition, definition_id)
if not definition:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Unknown background job task id {definition_id}.",
)
return definition
def _get_run(session: Session, run_id: int) -> JobRun:
run = session.get(JobRun, run_id)
if not run:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Unknown background job run id {run_id}.",
)
return run
def _last_run(session: Session, definition_id: int) -> JobRun | None:
return session.exec(
select(JobRun)
.where(JobRun.definition_id == definition_id)
.order_by(col(JobRun.id).desc())
).first()
def _to_task(session: Session, definition: JobDefinition) -> BackgroundJobTask:
last_run = _last_run(session, definition.id)
if last_run is None:
derived_status = "idle"
elif last_run.status == JobRunStatus.RUNNING:
derived_status = "running"
else:
derived_status = last_run.status.value
return BackgroundJobTask(
id=definition.id,
name=definition.name,
description=definition.description,
target_index=definition.target_index,
image=definition.image,
command=definition.command,
env=definition.env or {},
schedule=definition.schedule,
enabled=definition.enabled,
next_run_at=definition.next_run_at,
last_run=last_run,
status=derived_status,
)
def get_tasks(
session: Session, access_token: AccessTokenMetadata
) -> list[BackgroundJobTask]:
_require_super_admin(access_token)
definitions = session.exec(
select(JobDefinition).order_by(col(JobDefinition.id))
).all()
return [_to_task(session, definition) for definition in definitions]
def create_task(
session: Session,
access_token: AccessTokenMetadata,
payload: JobDefinitionCreateRequest,
) -> BackgroundJobTask:
_require_super_admin(access_token)
name = payload.name.strip()
if not name:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="Task name must not be empty.",
)
image = (payload.image or "").strip()
if not image:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="An image must be selected.",
)
if payload.schedule is not None and not croniter.is_valid(payload.schedule):
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=f"Invalid cron expression: '{payload.schedule}'.",
)
if session.exec(select(JobDefinition).where(JobDefinition.name == name)).first():
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail=f"A task named '{name}' already exists.",
)
definition = JobDefinition(
name=name,
image=image,
command=payload.command,
env=payload.env or {},
description=payload.description,
target_index=payload.target_index,
schedule=payload.schedule,
enabled=payload.enabled,
)
if definition.enabled and definition.schedule:
definition.next_run_at = runner.compute_next_run(definition.schedule)
session.add(definition)
session.commit()
session.refresh(definition)
logger.info("Created background job task '%s'.", name)
return _to_task(session, definition)
def delete_task(
session: Session, access_token: AccessTokenMetadata, definition_id: int
) -> None:
_require_super_admin(access_token)
definition = _get_definition(session, definition_id)
if runner.has_running_run(session, definition.id):
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail=f"'{definition.name}' is running. Stop the run first.",
)
runs = session.exec(
select(JobRun).where(JobRun.definition_id == definition.id)
).all()
for run in runs:
session.delete(run)
session.delete(definition)
session.commit()
logger.info(
"Deleted background job task '%s' (%d runs removed).",
definition.name,
len(runs),
)
def update_task(
session: Session,
access_token: AccessTokenMetadata,
definition_id: int,
payload: JobDefinitionUpdateRequest,
) -> BackgroundJobTask:
_require_super_admin(access_token)
changes = payload.model_dump(exclude_unset=True)
if changes.get("schedule") is not None and not croniter.is_valid(
changes["schedule"]
):
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail=f"Invalid cron expression: '{changes['schedule']}'.",
)
if "name" in changes:
name = (changes["name"] or "").strip()
if not name:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="Task name must not be empty.",
)
duplicate = session.exec(
select(JobDefinition).where(
JobDefinition.name == name,
JobDefinition.id != definition_id,
)
).first()
if duplicate:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail=f"A task named '{name}' already exists.",
)
changes["name"] = name
if "image" in changes:
image = (changes["image"] or "").strip()
if not image:
raise HTTPException(
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
detail="An image must be selected.",
)
changes["image"] = image
definition = _get_definition(session, definition_id)
for key, value in changes.items():
setattr(definition, key, value)
if "schedule" in changes or "enabled" in changes:
definition.next_run_at = (
runner.compute_next_run(definition.schedule)
if definition.enabled and definition.schedule
else None
)
session.add(definition)
session.commit()
session.refresh(definition)
return _to_task(session, definition)
def trigger_run(
session: Session, access_token: AccessTokenMetadata, definition_id: int
) -> JobRun:
_require_super_admin(access_token)
definition = _get_definition(session, definition_id)
if runner.has_running_run(session, definition.id):
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail=f"'{definition.name}' is already running.",
)
return runner.start_run(session, definition, JobTriggeredBy.MANUAL)
def get_task_runs(
session: Session,
access_token: AccessTokenMetadata,
definition_id: int,
limit: int,
) -> list[JobRun]:
_require_super_admin(access_token)
_get_definition(session, definition_id)
return session.exec(
select(JobRun)
.where(JobRun.definition_id == definition_id)
.order_by(col(JobRun.id).desc())
.limit(limit)
).all()
LOG_TAIL_LINES = 200
def _tail_log_lines(text: str, limit: int = LOG_TAIL_LINES) -> str:
lines = text.splitlines()
if len(lines) <= limit:
return text
return "\n".join(lines[-limit:])
def get_run_logs(
session: Session, access_token: AccessTokenMetadata, run_id: int
) -> JobRunLogs:
_require_super_admin(access_token)
run = _get_run(session, run_id)
if run.status == JobRunStatus.RUNNING and run.container_id:
try:
container = runner.get_docker_client().containers.get(run.container_id)
return JobRunLogs(
run_id=run_id,
status=run.status,
logs=container.logs(tail=LOG_TAIL_LINES).decode(
"utf-8", errors="replace"
),
)
except Exception: # noqa: BLE001
pass
return JobRunLogs(
run_id=run_id, status=run.status, logs=_tail_log_lines(run.logs or "")
)
def stop_run(
session: Session, access_token: AccessTokenMetadata, run_id: int
) -> JobRun:
_require_super_admin(access_token)
with runner.RUN_STATE_LOCK:
run = _get_run(session, run_id)
session.refresh(run)
if run.status != JobRunStatus.RUNNING or not run.container_id:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail=f"Run {run_id} is not running.",
)
requested_at = utcnow().isoformat(timespec="seconds") + "Z"
stop_message = f"Stop requested at {requested_at}."
try:
container = runner.get_docker_client().containers.get(run.container_id)
container.reload()
except NotFound as error:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail=f"Container for run {run_id} no longer exists.",
) from error
except Exception as error: # noqa: BLE001
logger.warning(
"Could not inspect run %s before stopping.", run_id, exc_info=True
)
raise HTTPException(
status_code=status.HTTP_502_BAD_GATEWAY,
detail=f"Could not inspect container for run {run_id}.",
) from error
stopped_by_request = False
if container.status not in ("exited", "dead"):
try:
container.stop(timeout=2)
stopped_by_request = True
except APIError as error:
if error.status_code != 304:
logger.warning("Could not stop run %s.", run_id, exc_info=True)
raise HTTPException(
status_code=status.HTTP_502_BAD_GATEWAY,
detail=f"Could not stop container for run {run_id}.",
) from error
except Exception as error: # noqa: BLE001
logger.warning("Could not stop run %s.", run_id, exc_info=True)
raise HTTPException(
status_code=status.HTTP_502_BAD_GATEWAY,
detail=f"Could not stop container for run {run_id}.",
) from error
container.reload()
exit_code = container.attrs["State"]["ExitCode"]
logs = container.logs().decode("utf-8", errors="replace")
logs = runner.append_system_log(logs, stop_message)
if stopped_by_request:
new_status = JobRunStatus.STOPPED
logs = runner.append_system_log(
logs, f"Container stopped (exit {exit_code})."
)
else:
new_status = (
JobRunStatus.SUCCEEDED if exit_code == 0 else JobRunStatus.FAILED
)
logs = runner.append_system_log(
logs, "Stop request arrived after the container had exited."
)
applied = runner.finalize_run(
session,
run,
new_status=new_status,
exit_code=exit_code,
logs=logs,
)
if not applied:
session.rollback()
session.refresh(run)
return run
session.commit()
runner.remove_container(container, run.id)
session.refresh(run)
return run
def get_available_images(access_token: AccessTokenMetadata) -> AvailableImages:
_require_super_admin(access_token)
images, detail = runner.list_registry_images()
return AvailableImages(images=images, detail=detail)
def docker_health(access_token: AccessTokenMetadata) -> DockerHealth:
_require_super_admin(access_token)
reachable, detail = runner.docker_reachable()
return DockerHealth(reachable=reachable, detail=detail)
def registry_health(access_token: AccessTokenMetadata) -> RegistryHealth:
_require_super_admin(access_token)
reachable, detail = runner.registry_reachable()
return RegistryHealth(
reachable=reachable, detail=detail, host=runner.registry_host()
)
@@ -0,0 +1,146 @@
from types import SimpleNamespace
import pytest
from fastapi import HTTPException
from sqlmodel import Session, SQLModel, create_engine
from inse.auth.model import UserRole
from . import runner, service
from .model import JobRun, JobRunStatus, JobTriggeredBy
class FakeContainer:
def __init__(
self, *, status: str, exit_code: int, logs: str, stop_error=None
):
self.status = status
self.attrs = {"State": {"ExitCode": exit_code}}
self._logs = logs
self.stop_calls = 0
self.removed = False
self.stop_error = stop_error
def reload(self) -> None:
pass
def stop(self, timeout: int) -> None:
assert timeout == 2
self.stop_calls += 1
if self.stop_error:
raise self.stop_error
self.status = "exited"
self.attrs["State"]["ExitCode"] = 143
def logs(self, tail=None) -> bytes:
return self._logs.encode()
def remove(self) -> None:
self.removed = True
@pytest.fixture()
def session():
engine = create_engine(
"sqlite:///:memory:", connect_args={"check_same_thread": False}
)
SQLModel.metadata.create_all(engine)
with Session(engine) as database_session:
yield database_session
def _token():
return SimpleNamespace(effective_role=UserRole.SUPER_ADMIN)
def _run(session: Session, status: JobRunStatus = JobRunStatus.RUNNING) -> JobRun:
run = JobRun(
definition_id=1,
container_id="container-id",
status=status,
triggered_by=JobTriggeredBy.MANUAL,
)
session.add(run)
session.commit()
session.refresh(run)
return run
def _use_container(monkeypatch, container: FakeContainer) -> None:
client = SimpleNamespace(
containers=SimpleNamespace(get=lambda container_id: container)
)
monkeypatch.setattr(runner, "get_docker_client", lambda: client)
def test_stop_running_container_records_stopped_and_system_logs(
session, monkeypatch
):
run = _run(session)
container = FakeContainer(status="running", exit_code=0, logs="Progress: 5/20")
_use_container(monkeypatch, container)
result = service.stop_run(session, _token(), run.id)
assert result.status == JobRunStatus.STOPPED
assert result.exit_code == 143
assert container.stop_calls == 1
assert container.removed is True
assert "Progress: 5/20" in result.logs
assert "[system] Stop requested at" in result.logs
assert "[system] Container stopped (exit 143)." in result.logs
def test_late_stop_preserves_successful_container_result(session, monkeypatch):
run = _run(session)
container = FakeContainer(
status="exited",
exit_code=0,
logs="Demo job finished successfully.",
)
_use_container(monkeypatch, container)
result = service.stop_run(session, _token(), run.id)
assert result.status == JobRunStatus.SUCCEEDED
assert result.exit_code == 0
assert container.stop_calls == 0
assert container.removed is True
assert "Demo job finished successfully." in result.logs
assert "Stop request arrived after the container had exited." in result.logs
def test_reconciler_keeps_running_container_after_backend_restart(
session, monkeypatch
):
run = _run(session)
container = FakeContainer(status="running", exit_code=0, logs="Partial output")
_use_container(monkeypatch, container)
runner.reconcile_runs(session)
session.refresh(run)
assert run.status == JobRunStatus.RUNNING
assert run.exit_code is None
assert container.stop_calls == 0
assert container.removed is False
def test_failed_docker_stop_leaves_database_run_running(session, monkeypatch):
run = _run(session)
container = FakeContainer(
status="running",
exit_code=0,
logs="Partial output",
stop_error=RuntimeError("Docker unavailable"),
)
_use_container(monkeypatch, container)
with pytest.raises(HTTPException) as error:
service.stop_run(session, _token(), run.id)
session.refresh(run)
assert run.status == JobRunStatus.RUNNING
assert error.value.status_code == 502
assert run.finished_at is None
assert container.removed is False
+20 -2
View File
@@ -7,6 +7,7 @@ that can be adjusted via environment variables.
from functools import lru_cache from functools import lru_cache
import logging import logging
from pathlib import Path
from typing import Dict, List, Literal, Optional from typing import Dict, List, Literal, Optional
from pydantic_settings import BaseSettings, SettingsConfigDict from pydantic_settings import BaseSettings, SettingsConfigDict
from dotenv import load_dotenv from dotenv import load_dotenv
@@ -14,7 +15,10 @@ from dotenv import load_dotenv
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
load_dotenv() # Anchor the .env to this file's directory so it loads regardless of the
# process working directory.
ENV_FILE = Path(__file__).resolve().parent / ".env"
load_dotenv(ENV_FILE)
class Settings(BaseSettings): class Settings(BaseSettings):
@@ -43,6 +47,20 @@ class Settings(BaseSettings):
llm_api_key: Optional[str] = None llm_api_key: Optional[str] = None
llm_model: Optional[str] = None llm_model: Optional[str] = None
# Background job runner config (Docker-out-of-Docker)
background_jobs_image: str = "docker.nes.uni-due.de/inse/background-jobs:latest"
background_jobs_scheduler_enabled: bool = True
background_jobs_tick_seconds: int = 5
# Pull the job image from the registry before each run so an updated tag
# (e.g. :latest) is picked up. Disable for local image development, where
# a locally built image would otherwise be overwritten by the registry.
background_jobs_pull_before_run: bool = True
# Credentials for pulling the job image from a private registry (e.g. the
# Nexus at docker.nes.uni-due.de). Needed because the runner pulls via the
# Docker SDK inside the service container, which has no `docker login` creds.
background_jobs_registry_username: Optional[str] = None
background_jobs_registry_password: Optional[str] = None
# Sentence Transformers config # Sentence Transformers config
sentence_transformers_model_name: str = "intfloat/multilingual-e5-base" sentence_transformers_model_name: str = "intfloat/multilingual-e5-base"
@@ -52,7 +70,7 @@ class Settings(BaseSettings):
elasticsearch_inse_url: Optional[str] = None elasticsearch_inse_url: Optional[str] = None
elasticsearch_inse_api_key: Optional[str] = None elasticsearch_inse_api_key: Optional[str] = None
model_config = SettingsConfigDict(env_file=".env") model_config = SettingsConfigDict(env_file=str(ENV_FILE))
allowed_origins: List[str] = ["http://localhost:4200"] allowed_origins: List[str] = ["http://localhost:4200"]
+14
View File
@@ -6,6 +6,7 @@ for fastapi that loads the service and the
webapp. webapp.
""" """
import asyncio
from contextlib import asynccontextmanager, contextmanager from contextlib import asynccontextmanager, contextmanager
import logging import logging
@@ -44,6 +45,8 @@ from inse.bookmarks.router import router as bookmarks_router
from inse.institutions.router import router as institutions_router from inse.institutions.router import router as institutions_router
from inse.database import create_db_and_tables, get_session from inse.database import create_db_and_tables, get_session
from inse.auth.service import create_predefined_accounts from inse.auth.service import create_predefined_accounts
from inse.background_jobs.router import router as background_jobs_router
from inse.background_jobs.runner import scheduler_loop as background_jobs_scheduler_loop
from . import config from . import config
from .service import router as service_router from .service import router as service_router
@@ -77,7 +80,17 @@ async def lifespan(app: FastAPI):
create_db_and_tables() create_db_and_tables()
with contextmanager(get_session)() as session: with contextmanager(get_session)() as session:
create_predefined_accounts(session, "../data/predefined_accounts.json") create_predefined_accounts(session, "../data/predefined_accounts.json")
background_jobs_scheduler_task = None
if settings.background_jobs_scheduler_enabled:
background_jobs_scheduler_task = asyncio.create_task(
background_jobs_scheduler_loop()
)
yield yield
if background_jobs_scheduler_task is not None:
background_jobs_scheduler_task.cancel()
logger.info("Shutting down the application...") logger.info("Shutting down the application...")
@@ -122,6 +135,7 @@ app.include_router(dashboard_router)
app.include_router(dfg_institutions_router) app.include_router(dfg_institutions_router)
app.include_router(dfg_persons_router) app.include_router(dfg_persons_router)
app.include_router(bookmarks_router) app.include_router(bookmarks_router)
app.include_router(background_jobs_router)
app.include_router(eu_organizations_router) app.include_router(eu_organizations_router)
app.add_middleware( app.add_middleware(
@@ -13,6 +13,7 @@ from starlette.responses import Response
NO_STORE_PATH_PREFIXES = ( NO_STORE_PATH_PREFIXES = (
"/api/auth/v2", "/api/auth/v2",
"/api/accounts", "/api/accounts",
"/api/background-jobs",
"/api/bookmarks", "/api/bookmarks",
"/api/organizations", "/api/organizations",
"/api/dashboard", "/api/dashboard",
@@ -24,7 +25,6 @@ NO_STORE_PATH_FRAGMENTS = (
"/company-connections", "/company-connections",
"/primary-category-aggregations", "/primary-category-aggregations",
) )
# POST is opt-out. Add any endpoint here that MUTATES state (create/update/delete/ # POST is opt-out. Add any endpoint here that MUTATES state (create/update/delete/
# trigger side effects), even if it "usually" returns 200. # trigger side effects), even if it "usually" returns 200.
EXCLUDED_POST_PATHS = ( EXCLUDED_POST_PATHS = (
@@ -0,0 +1,53 @@
from fastapi import FastAPI
from fastapi.testclient import TestClient
from inse.middleware.etag_cache import ETagCacheMiddleware
def _app_with_counter():
app = FastAPI()
calls = {"get": 0, "post": 0}
@app.get("/api/background-jobs/tasks")
def get_tasks():
calls["get"] += 1
return {"call": calls["get"]}
@app.post("/api/background-jobs/tasks/4/run")
def run_task():
calls["post"] += 1
return {"call": calls["post"]}
app.add_middleware(ETagCacheMiddleware, ttl=120)
return app, calls
def test_background_job_gets_are_never_cached():
app, calls = _app_with_counter()
with TestClient(app) as client:
first = client.get("/api/background-jobs/tasks")
second = client.get(
"/api/background-jobs/tasks",
headers={"If-None-Match": first.headers.get("etag", "")},
)
assert first.status_code == 200
assert second.status_code == 200
assert first.json() == {"call": 1}
assert second.json() == {"call": 2}
assert calls["get"] == 2
def test_background_job_post_side_effects_are_never_replayed_from_cache():
app, calls = _app_with_counter()
with TestClient(app) as client:
first = client.post("/api/background-jobs/tasks/4/run")
second = client.post("/api/background-jobs/tasks/4/run")
assert first.status_code == 200
assert second.status_code == 200
assert first.json() == {"call": 1}
assert second.json() == {"call": 2}
assert calls["post"] == 2
+99 -38
View File
@@ -12,16 +12,18 @@ from inse.exceptions import ElasticsearchException
from ..integrations import elasticsearch, llm from ..integrations import elasticsearch, llm
from ..persons.logic import find_ude_author_by_name, get_author_name_by_id from ..persons.logic import find_ude_author_by_name, get_author_name_by_id
from ..topics.logic import vector_search_topics from ..topics.logic import vector_search_topics_batch
from .model import MatchedTopic, MentionedPerson, NewsArticle, NewsArticleDetail, NewsPage from .model import MatchedTopic, MentionedPerson, NewsArticle, NewsArticleDetail, NewsPage
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
TOPIC_LIMIT = 4
TOPIC_QUERY_CONTENT_CHARS = 300
TOPIC_NUM_CANDIDATES = 100 TOPIC_NUM_CANDIDATES = 100
TOPIC_SIMILARITY = 0.5 TOPIC_SIMILARITY = 0.5
TOPIC_MATCHES_PER_KEYWORD = 1
TOPICS_INDEX = "aktuell_openalex_topics"
TOPICS_INDEX_MAX_PAIRS = 100
_SESSION_TOPIC_CACHE: dict[str, list] = {}
KEYWORD_LIMIT = 6 KEYWORD_LIMIT = 6
KEYWORD_CONTENT_CHARS = 4000 KEYWORD_CONTENT_CHARS = 4000
@@ -253,14 +255,14 @@ async def get_news_by_id(news_id: str) -> NewsArticleDetail:
source = response.get("_source", {}) source = response.get("_source", {})
relevant, authors, cached_keywords, postproc_id = await _get_postproc_labels(news_id) relevant, authors, cached_keywords, postproc_id = await _get_postproc_labels(news_id)
keywords = await _get_article_keywords( keywords, postproc_id = await _get_article_keywords(
news_id, news_id,
postproc_id, postproc_id,
cached_keywords, cached_keywords,
source.get("maintitle"), source.get("maintitle"),
source.get("full_content"), source.get("full_content"),
) )
topics = await _match_topics_for_keywords(keywords) topics = await _get_article_topics(news_id, keywords)
return NewsArticleDetail( return NewsArticleDetail(
id=response.get("_id"), id=response.get("_id"),
@@ -282,15 +284,15 @@ async def _get_article_keywords(
cached_keywords: list, cached_keywords: list,
maintitle: str | None, maintitle: str | None,
full_content: str | None, full_content: str | None,
) -> list: ) -> tuple[list, str | None]:
if cached_keywords: if cached_keywords:
return cached_keywords return cached_keywords, postproc_id
text = " ".join( text = " ".join(
part for part in (maintitle, (full_content or "")[:KEYWORD_CONTENT_CHARS]) if part part for part in (maintitle, (full_content or "")[:KEYWORD_CONTENT_CHARS]) if part
).strip() ).strip()
if not text: if not text:
return [] return [], postproc_id
raw = await llm.call( raw = await llm.call(
system_prompt=KEYWORD_SYSTEM_PROMPT, system_prompt=KEYWORD_SYSTEM_PROMPT,
@@ -300,9 +302,61 @@ async def _get_article_keywords(
keywords = _parse_keywords(raw) keywords = _parse_keywords(raw)
if keywords: if keywords:
await _store_keywords(news_id, postproc_id, keywords) postproc_id = await _store_keywords(news_id, postproc_id, keywords)
return keywords return keywords, postproc_id
async def _get_article_topics(news_id: str, keywords: list) -> list:
indexed = await get_article_topics_from_index(news_id)
if indexed:
return indexed
if news_id in _SESSION_TOPIC_CACHE:
return _SESSION_TOPIC_CACHE[news_id]
topics = await _match_topics_for_keywords(keywords)
if topics:
_SESSION_TOPIC_CACHE[news_id] = topics
return topics
async def get_article_topics_from_index(news_id: str) -> list:
try:
response = await elasticsearch.search(
index=TOPICS_INDEX,
query={"term": {"news_id.keyword": news_id}},
source=["keyword", "topic_matches"],
size=TOPICS_INDEX_MAX_PAIRS,
cluster="inse",
)
except Exception:
logger.exception(f"Topic-index lookup for {news_id} failed.")
return []
matched = []
seen_ids = set()
for hit in response.get("hits", {}).get("hits", []):
source = hit.get("_source", {})
keyword = source.get("keyword")
for match in source.get("topic_matches") or []:
topic_id = match.get("topic_id")
if not topic_id or topic_id in seen_ids:
continue
seen_ids.add(topic_id)
matched.append(
MatchedTopic(
id=topic_id,
display_name=match.get("topic_display_name"),
subfield_name=match.get("subfield"),
field_name=match.get("field"),
domain_name=match.get("domain"),
source_keyword=keyword,
)
)
return matched
def _parse_keywords(raw: str) -> list: def _parse_keywords(raw: str) -> list:
@@ -330,7 +384,8 @@ def _parse_keywords(raw: str) -> list:
return keywords[:KEYWORD_LIMIT] return keywords[:KEYWORD_LIMIT]
async def _store_keywords(news_id: str, postproc_id: str | None, keywords: list) -> None: async def _store_keywords(news_id: str, postproc_id: str | None, keywords: list) -> str | None:
"""Caches the keywords and returns the postproc document id they landed in."""
try: try:
if postproc_id: if postproc_id:
await elasticsearch.update( await elasticsearch.update(
@@ -339,42 +394,48 @@ async def _store_keywords(news_id: str, postproc_id: str | None, keywords: list)
doc={"keywords": keywords}, doc={"keywords": keywords},
cluster="inse", cluster="inse",
) )
else: return postproc_id
await elasticsearch.index_doc(
index="aktuell_postproc", await elasticsearch.index_doc(
doc_id=news_id, index="aktuell_postproc",
document={"news_id": news_id, "keywords": keywords}, doc_id=news_id,
cluster="inse", document={"news_id": news_id, "keywords": keywords},
) cluster="inse",
)
return news_id
except Exception: except Exception:
logger.exception(f"Failed to cache keywords for {news_id}.") logger.exception(f"Failed to cache keywords for {news_id}.")
return postproc_id
async def _match_topics_for_keywords(keywords: list) -> list: async def _match_topics_for_keywords(keywords: list) -> list:
if not keywords:
return []
try:
response = await vector_search_topics_batch(keywords=keywords)
except Exception:
logger.exception(f"Topic-Matching fuer {len(keywords)} Keywords fehlgeschlagen.")
return []
matched = [] matched = []
seen_ids = set() seen_ids = set()
for keyword in keywords: for match in response.results or []:
try: topic = match.topic
response = await vector_search_topics(query=keyword, limit=TOPIC_MATCHES_PER_KEYWORD) if not topic or not topic.id or topic.id in seen_ids:
except Exception:
logger.exception(f"Topic-Matching fuer Keyword '{keyword}' fehlgeschlagen.")
continue continue
seen_ids.add(topic.id)
for topic in response.results or []: matched.append(
if not topic.id or topic.id in seen_ids: MatchedTopic(
continue id=topic.id,
seen_ids.add(topic.id) display_name=topic.display_name,
matched.append( subfield_name=topic.subfield.display_name if topic.subfield else None,
MatchedTopic( field_name=topic.var_field.display_name if topic.var_field else None,
id=topic.id, domain_name=topic.domain.display_name if topic.domain else None,
display_name=topic.display_name, source_keyword=match.keyword,
subfield_name=topic.subfield.display_name if topic.subfield else None,
field_name=topic.var_field.display_name if topic.var_field else None,
domain_name=topic.domain.display_name if topic.domain else None,
source_keyword=keyword,
)
) )
)
return matched return matched
+1
View File
@@ -23,3 +23,4 @@ class Tags(StrEnum):
DFG_INSTITUTIONS = "DFG Institutions" DFG_INSTITUTIONS = "DFG Institutions"
DFG_PERSONS = "DFG Persons" DFG_PERSONS = "DFG Persons"
BACKGROUND_JOBS = "Background Jobs"
+45 -44
View File
@@ -49,7 +49,7 @@ In your project:
npm link npm link
``` ```
__Note for Windows users:__ The Angular CLI has troubles to use linked npm packages. **Note for Windows users:** The Angular CLI has troubles to use linked npm packages.
Please refer to this issue <https://github.com/angular/angular-cli/issues/8284> for a solution / workaround. Please refer to this issue <https://github.com/angular/angular-cli/issues/8284> for a solution / workaround.
Published packages are not effected by this issue. Published packages are not effected by this issue.
@@ -58,22 +58,22 @@ Published packages are not effected by this issue.
In your Angular project: In your Angular project:
```typescript ```typescript
import { ApplicationConfig } from '@angular/core'; import { ApplicationConfig } from '@angular/core';
import { provideHttpClient } from '@angular/common/http'; import { provideHttpClient } from '@angular/common/http';
import { provideApi } from ''; import { provideApi } from '';
export const appConfig: ApplicationConfig = { export const appConfig: ApplicationConfig = {
providers: [ providers: [
// ... // ...
provideHttpClient(), provideHttpClient(),
provideApi() provideApi(),
], ],
}; };
``` ```
**NOTE** **NOTE**
If you're still using `AppModule` and haven't [migrated](https://angular.dev/reference/migrations/standalone) yet, you can still import an Angular module: If you're still using `AppModule` and haven't [migrated](https://angular.dev/reference/migrations/standalone) yet, you can still import an Angular module:
```typescript ```typescript
import { ApiModule } from ''; import { ApiModule } from '';
``` ```
@@ -86,11 +86,11 @@ import { provideHttpClient } from '@angular/common/http';
import { provideApi } from ''; import { provideApi } from '';
export const appConfig: ApplicationConfig = { export const appConfig: ApplicationConfig = {
providers: [ providers: [
// ... // ...
provideHttpClient(), provideHttpClient(),
provideApi('http://localhost:9999') provideApi('http://localhost:9999'),
], ],
}; };
``` ```
@@ -101,15 +101,15 @@ import { provideHttpClient } from '@angular/common/http';
import { provideApi } from ''; import { provideApi } from '';
export const appConfig: ApplicationConfig = { export const appConfig: ApplicationConfig = {
providers: [ providers: [
// ... // ...
provideHttpClient(), provideHttpClient(),
provideApi({ provideApi({
withCredentials: true, withCredentials: true,
username: 'user', username: 'user',
password: 'password' password: 'password',
}) }),
], ],
}; };
``` ```
@@ -120,21 +120,22 @@ import { provideHttpClient } from '@angular/common/http';
import { provideApi, Configuration } from ''; import { provideApi, Configuration } from '';
export const appConfig: ApplicationConfig = { export const appConfig: ApplicationConfig = {
providers: [ providers: [
// ... // ...
provideHttpClient(), provideHttpClient(),
{ {
provide: Configuration, provide: Configuration,
useFactory: (authService: AuthService) => new Configuration({ useFactory: (authService: AuthService) =>
basePath: 'http://localhost:9999', new Configuration({
withCredentials: true, basePath: 'http://localhost:9999',
username: authService.getUsername(), withCredentials: true,
password: authService.getPassword(), username: authService.getUsername(),
}), password: authService.getPassword(),
deps: [AuthService], }),
multi: false deps: [AuthService],
} multi: false,
], },
],
}; };
``` ```
@@ -151,12 +152,12 @@ import { HttpClientModule } from '@angular/common/http';
import { environment } from '../environments/environment'; import { environment } from '../environments/environment';
export const appConfig: ApplicationConfig = { export const appConfig: ApplicationConfig = {
providers: [ providers: [
// ... // ...
provideHttpClient(), provideHttpClient(),
provideUserApi(environment.basePath), provideUserApi(environment.basePath),
provideAdminApi(environment.basePath), provideAdminApi(environment.basePath),
], ],
}; };
``` ```
@@ -176,8 +177,8 @@ Example value for use in your Configuration-Provider:
```typescript ```typescript
new Configuration({ new Configuration({
encodeParam: (param: Param) => myFancyParamEncoder(param), encodeParam: (param: Param) => myFancyParamEncoder(param),
}) });
``` ```
[parameter-locations-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-locations [parameter-locations-url]: https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#parameter-locations
+87 -61
View File
@@ -7,77 +7,103 @@
* https://openapi-generator.tech * https://openapi-generator.tech
* Do not edit the class manually. * Do not edit the class manually.
*/ */
import { HttpHeaders, HttpParams, HttpParameterCodec } from '@angular/common/http'; import {
HttpHeaders,
HttpParams,
HttpParameterCodec,
} from '@angular/common/http';
import { CustomHttpParameterCodec } from './encoder'; import { CustomHttpParameterCodec } from './encoder';
import { Configuration } from './configuration'; import { Configuration } from './configuration';
export class BaseService { export class BaseService {
protected basePath = 'http://localhost:8000'; protected basePath = 'http://localhost:8000';
public defaultHeaders = new HttpHeaders(); public defaultHeaders = new HttpHeaders();
public configuration: Configuration; public configuration: Configuration;
public encoder: HttpParameterCodec; public encoder: HttpParameterCodec;
constructor(basePath?: string|string[], configuration?: Configuration) { constructor(basePath?: string | string[], configuration?: Configuration) {
this.configuration = configuration || new Configuration(); this.configuration = configuration || new Configuration();
if (typeof this.configuration.basePath !== 'string') { if (typeof this.configuration.basePath !== 'string') {
const firstBasePath = Array.isArray(basePath) ? basePath[0] : undefined; const firstBasePath = Array.isArray(basePath) ? basePath[0] : undefined;
if (firstBasePath != undefined) { if (firstBasePath != undefined) {
basePath = firstBasePath; basePath = firstBasePath;
} }
if (typeof basePath !== 'string') { if (typeof basePath !== 'string') {
basePath = this.basePath; basePath = this.basePath;
} }
this.configuration.basePath = basePath; this.configuration.basePath = basePath;
}
this.encoder = this.configuration.encoder || new CustomHttpParameterCodec();
} }
this.encoder = this.configuration.encoder || new CustomHttpParameterCodec();
}
protected canConsumeForm(consumes: string[]): boolean { protected canConsumeForm(consumes: string[]): boolean {
return consumes.indexOf('multipart/form-data') !== -1; return consumes.indexOf('multipart/form-data') !== -1;
} }
protected addToHttpParams(httpParams: HttpParams, value: any, key?: string, isDeep: boolean = false): HttpParams { protected addToHttpParams(
// If the value is an object (but not a Date), recursively add its keys. httpParams: HttpParams,
if (typeof value === 'object' && !(value instanceof Date)) { value: any,
return this.addToHttpParamsRecursive(httpParams, value, isDeep ? key : undefined, isDeep); key?: string,
} isDeep: boolean = false,
return this.addToHttpParamsRecursive(httpParams, value, key); ): HttpParams {
// If the value is an object (but not a Date), recursively add its keys.
if (typeof value === 'object' && !(value instanceof Date)) {
return this.addToHttpParamsRecursive(
httpParams,
value,
isDeep ? key : undefined,
isDeep,
);
} }
return this.addToHttpParamsRecursive(httpParams, value, key);
}
protected addToHttpParamsRecursive(httpParams: HttpParams, value?: any, key?: string, isDeep: boolean = false): HttpParams { protected addToHttpParamsRecursive(
if (value === null || value === undefined) { httpParams: HttpParams,
return httpParams; value?: any,
} key?: string,
if (typeof value === 'object') { isDeep: boolean = false,
// If JSON format is preferred, key must be provided. ): HttpParams {
if (key != null) { if (value === null || value === undefined) {
return isDeep return httpParams;
? Object.keys(value as Record<string, any>).reduce(
(hp, k) => hp.append(`${key}[${k}]`, value[k]),
httpParams,
)
: httpParams.append(key, JSON.stringify(value));
}
// Otherwise, if it's an array, add each element.
if (Array.isArray(value)) {
value.forEach(elem => httpParams = this.addToHttpParamsRecursive(httpParams, elem, key));
} else if (value instanceof Date) {
if (key != null) {
httpParams = httpParams.append(key, value.toISOString());
} else {
throw Error("key may not be null if value is Date");
}
} else {
Object.keys(value).forEach(k => {
const paramKey = key ? `${key}.${k}` : k;
httpParams = this.addToHttpParamsRecursive(httpParams, value[k], paramKey);
});
}
return httpParams;
} else if (key != null) {
return httpParams.append(key, value);
}
throw Error("key may not be null if value is not object or array");
} }
if (typeof value === 'object') {
// If JSON format is preferred, key must be provided.
if (key != null) {
return isDeep
? Object.keys(value as Record<string, any>).reduce(
(hp, k) => hp.append(`${key}[${k}]`, value[k]),
httpParams,
)
: httpParams.append(key, JSON.stringify(value));
}
// Otherwise, if it's an array, add each element.
if (Array.isArray(value)) {
value.forEach(
(elem) =>
(httpParams = this.addToHttpParamsRecursive(httpParams, elem, key)),
);
} else if (value instanceof Date) {
if (key != null) {
httpParams = httpParams.append(key, value.toISOString());
} else {
throw Error('key may not be null if value is Date');
}
} else {
Object.keys(value).forEach((k) => {
const paramKey = key ? `${key}.${k}` : k;
httpParams = this.addToHttpParamsRecursive(
httpParams,
value[k],
paramKey,
);
});
}
return httpParams;
} else if (key != null) {
return httpParams.append(key, value);
}
throw Error('key may not be null if value is not object or array');
}
} }
+32 -20
View File
@@ -1,30 +1,42 @@
import { NgModule, ModuleWithProviders, SkipSelf, Optional } from '@angular/core'; import {
NgModule,
ModuleWithProviders,
SkipSelf,
Optional,
} from '@angular/core';
import { Configuration } from './configuration'; import { Configuration } from './configuration';
import { HttpClient } from '@angular/common/http'; import { HttpClient } from '@angular/common/http';
@NgModule({ @NgModule({
imports: [], imports: [],
declarations: [], declarations: [],
exports: [], exports: [],
providers: [] providers: [],
}) })
export class ApiModule { export class ApiModule {
public static forRoot(configurationFactory: () => Configuration): ModuleWithProviders<ApiModule> { public static forRoot(
return { configurationFactory: () => Configuration,
ngModule: ApiModule, ): ModuleWithProviders<ApiModule> {
providers: [ { provide: Configuration, useFactory: configurationFactory } ] return {
}; ngModule: ApiModule,
} providers: [{ provide: Configuration, useFactory: configurationFactory }],
};
}
constructor( @Optional() @SkipSelf() parentModule: ApiModule, constructor(
@Optional() http: HttpClient) { @Optional() @SkipSelf() parentModule: ApiModule,
if (parentModule) { @Optional() http: HttpClient,
throw new Error('ApiModule is already loaded. Import in your base AppModule only.'); ) {
} if (parentModule) {
if (!http) { throw new Error(
throw new Error('You need to import the HttpClientModule in your AppModule! \n' + 'ApiModule is already loaded. Import in your base AppModule only.',
'See also https://github.com/angular/angular/issues/20575'); );
}
} }
if (!http) {
throw new Error(
'You need to import the HttpClientModule in your AppModule! \n' +
'See also https://github.com/angular/angular/issues/20575',
);
}
}
} }
+29 -1
View File
@@ -2,6 +2,8 @@ export * from './auth.service';
import { AuthService } from './auth.service'; import { AuthService } from './auth.service';
export * from './authorsV2.service'; export * from './authorsV2.service';
import { AuthorsV2Service } from './authorsV2.service'; import { AuthorsV2Service } from './authorsV2.service';
export * from './backgroundJobs.service';
import { BackgroundJobsService } from './backgroundJobs.service';
export * from './bookmarks.service'; export * from './bookmarks.service';
import { BookmarksService } from './bookmarks.service'; import { BookmarksService } from './bookmarks.service';
export * from './companyConnections.service'; export * from './companyConnections.service';
@@ -46,4 +48,30 @@ export * from './works.service';
import { WorksService } from './works.service'; import { WorksService } from './works.service';
export * from './worksV2.service'; export * from './worksV2.service';
import { WorksV2Service } from './worksV2.service'; import { WorksV2Service } from './worksV2.service';
export const APIS = [AuthService, AuthorsV2Service, BookmarksService, CompanyConnectionsService, DFGInstitutionsService, DFGPersonsService, DashboardService, FundingService, INSEServiceService, InstitutionsService, InstitutionsV2Service, KeywordsService, NewsService, OrganizationService, PatentsService, PersonNetworkService, PersonsService, ProjectsService, RankingService, TopicsService, TopicsV2Service, UniversityRankingsService, WorksService, WorksV2Service]; export const APIS = [
AuthService,
AuthorsV2Service,
BackgroundJobsService,
BookmarksService,
CompanyConnectionsService,
DFGInstitutionsService,
DFGPersonsService,
DashboardService,
FundingService,
INSEServiceService,
InstitutionsService,
InstitutionsV2Service,
KeywordsService,
NewsService,
OrganizationService,
PatentsService,
PersonNetworkService,
PersonsService,
ProjectsService,
RankingService,
TopicsService,
TopicsV2Service,
UniversityRankingsService,
WorksService,
WorksV2Service,
];
File diff suppressed because it is too large Load Diff
+221 -121
View File
@@ -9,12 +9,18 @@
*/ */
/* tslint:disable:no-unused-variable member-ordering */ /* tslint:disable:no-unused-variable member-ordering */
import { Inject, Injectable, Optional } from '@angular/core'; import { Inject, Injectable, Optional } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams, import {
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext HttpClient,
} from '@angular/common/http'; HttpHeaders,
import { CustomHttpParameterCodec } from '../encoder'; HttpParams,
import { Observable } from 'rxjs'; HttpResponse,
HttpEvent,
HttpParameterCodec,
HttpContext,
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
// @ts-ignore // @ts-ignore
import { AuthorPage } from '../model/authorPage'; import { AuthorPage } from '../model/authorPage';
@@ -22,137 +28,231 @@ import { AuthorPage } from '../model/authorPage';
import { HTTPValidationError } from '../model/hTTPValidationError'; import { HTTPValidationError } from '../model/hTTPValidationError';
// @ts-ignore // @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration'; import { Configuration } from '../configuration';
import { BaseService } from '../api.base.service'; import { BaseService } from '../api.base.service';
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root',
}) })
export class AuthorsV2Service extends BaseService { export class AuthorsV2Service extends BaseService {
constructor(
protected httpClient: HttpClient,
@Optional() @Inject(BASE_PATH) basePath: string | string[],
@Optional() configuration?: Configuration,
) {
super(basePath, configuration);
}
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { /**
super(basePath, configuration); * Returns a paginated list of authors for a given search term based on their display name.
* @endpoint get /api/authors/v2/autocomplete/selector
* @param query A search term to filter authors by (partial matches allowed).
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public autocompleteAuthorsForSelector(
query?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<AuthorPage>;
public autocompleteAuthorsForSelector(
query?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<AuthorPage>>;
public autocompleteAuthorsForSelector(
query?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<AuthorPage>>;
public autocompleteAuthorsForSelector(
query?: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>query,
'query',
);
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
} }
/** const localVarHttpContext: HttpContext =
* Returns a paginated list of authors for a given search term based on their display name. options?.context ?? new HttpContext();
* @endpoint get /api/authors/v2/autocomplete/selector
* @param query A search term to filter authors by (partial matches allowed).
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public autocompleteAuthorsForSelector(query?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AuthorPage>;
public autocompleteAuthorsForSelector(query?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AuthorPage>>;
public autocompleteAuthorsForSelector(query?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AuthorPage>>;
public autocompleteAuthorsForSelector(query?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
let localVarQueryParameters = new HttpParams({encoder: this.encoder}); const localVarTransferCache: boolean = options?.transferCache ?? true;
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>query, 'query');
let localVarHeaders = this.defaultHeaders; let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ let localVarPath = `/api/authors/v2/autocomplete/selector`;
'application/json' const { basePath, withCredentials } = this.configuration;
]); return this.httpClient.request<AuthorPage>(
if (localVarHttpHeaderAcceptSelected !== undefined) { 'get',
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); `${basePath}${localVarPath}`,
} {
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); /**
* Returns a paginated list of authors for a given list of author IDs.
const localVarTransferCache: boolean = options?.transferCache ?? true; * @endpoint get /api/authors/v2/authors/id
* @param authorIds A list of author IDs to retrieve.
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
let responseType_: 'text' | 'json' | 'blob' = 'json'; * @param reportProgress flag to report request and response progress.
if (localVarHttpHeaderAcceptSelected) { */
if (localVarHttpHeaderAcceptSelected.startsWith('text')) { public getAuthorsByIds(
responseType_ = 'text'; authorIds?: Array<string>,
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { observe?: 'body',
responseType_ = 'json'; reportProgress?: boolean,
} else { options?: {
responseType_ = 'blob'; httpHeaderAccept?: 'application/json';
} context?: HttpContext;
} transferCache?: boolean;
},
let localVarPath = `/api/authors/v2/autocomplete/selector`; ): Observable<AuthorPage>;
const { basePath, withCredentials } = this.configuration; public getAuthorsByIds(
return this.httpClient.request<AuthorPage>('get', `${basePath}${localVarPath}`, authorIds?: Array<string>,
{ observe?: 'response',
context: localVarHttpContext, reportProgress?: boolean,
params: localVarQueryParameters, options?: {
responseType: <any>responseType_, httpHeaderAccept?: 'application/json';
...(withCredentials ? { withCredentials } : {}), context?: HttpContext;
headers: localVarHeaders, transferCache?: boolean;
observe: observe, },
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), ): Observable<HttpResponse<AuthorPage>>;
reportProgress: reportProgress public getAuthorsByIds(
} authorIds?: Array<string>,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<AuthorPage>>;
public getAuthorsByIds(
authorIds?: Array<string>,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
if (authorIds) {
authorIds.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>element,
'author_ids',
); );
});
} }
/** let localVarHeaders = this.defaultHeaders;
* Returns a paginated list of authors for a given list of author IDs.
* @endpoint get /api/authors/v2/authors/id
* @param authorIds A list of author IDs to retrieve.
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getAuthorsByIds(authorIds?: Array<string>, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AuthorPage>;
public getAuthorsByIds(authorIds?: Array<string>, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AuthorPage>>;
public getAuthorsByIds(authorIds?: Array<string>, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AuthorPage>>;
public getAuthorsByIds(authorIds?: Array<string>, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
let localVarQueryParameters = new HttpParams({encoder: this.encoder}); const localVarHttpHeaderAcceptSelected: string | undefined =
if (authorIds) { options?.httpHeaderAccept ??
authorIds.forEach((element) => { this.configuration.selectHeaderAccept(['application/json']);
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, if (localVarHttpHeaderAcceptSelected !== undefined) {
<any>element, 'author_ids'); localVarHeaders = localVarHeaders.set(
}) 'Accept',
} localVarHttpHeaderAcceptSelected,
);
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/authors/v2/authors/id`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<AuthorPage>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
} }
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/authors/v2/authors/id`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<AuthorPage>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
} }
File diff suppressed because it is too large Load Diff
+365 -190
View File
@@ -9,12 +9,18 @@
*/ */
/* tslint:disable:no-unused-variable member-ordering */ /* tslint:disable:no-unused-variable member-ordering */
import { Inject, Injectable, Optional } from '@angular/core'; import { Inject, Injectable, Optional } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams, import {
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext HttpClient,
} from '@angular/common/http'; HttpHeaders,
import { CustomHttpParameterCodec } from '../encoder'; HttpParams,
import { Observable } from 'rxjs'; HttpResponse,
HttpEvent,
HttpParameterCodec,
HttpContext,
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
// @ts-ignore // @ts-ignore
import { CreatePersonBookmark } from '../model/createPersonBookmark'; import { CreatePersonBookmark } from '../model/createPersonBookmark';
@@ -24,206 +30,375 @@ import { HTTPValidationError } from '../model/hTTPValidationError';
import { PersonBookmarkResponse } from '../model/personBookmarkResponse'; import { PersonBookmarkResponse } from '../model/personBookmarkResponse';
// @ts-ignore // @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration'; import { Configuration } from '../configuration';
import { BaseService } from '../api.base.service'; import { BaseService } from '../api.base.service';
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root',
}) })
export class BookmarksService extends BaseService { export class BookmarksService extends BaseService {
constructor(
protected httpClient: HttpClient,
@Optional() @Inject(BASE_PATH) basePath: string | string[],
@Optional() configuration?: Configuration,
) {
super(basePath, configuration);
}
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { /**
super(basePath, configuration); * Bookmark Person
* @endpoint put /api/bookmarks/persons/{person_id}
* @param personId
* @param createPersonBookmark
* @param secureFgpAcc
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public bookmarkPerson(
personId: string,
createPersonBookmark: CreatePersonBookmark,
secureFgpAcc?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<PersonBookmarkResponse>;
public bookmarkPerson(
personId: string,
createPersonBookmark: CreatePersonBookmark,
secureFgpAcc?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<PersonBookmarkResponse>>;
public bookmarkPerson(
personId: string,
createPersonBookmark: CreatePersonBookmark,
secureFgpAcc?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<PersonBookmarkResponse>>;
public bookmarkPerson(
personId: string,
createPersonBookmark: CreatePersonBookmark,
secureFgpAcc?: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (personId === null || personId === undefined) {
throw new Error(
'Required parameter personId was null or undefined when calling bookmarkPerson.',
);
}
if (createPersonBookmark === null || createPersonBookmark === undefined) {
throw new Error(
'Required parameter createPersonBookmark was null or undefined when calling bookmarkPerson.',
);
} }
/** let localVarHeaders = this.defaultHeaders;
* Bookmark Person
* @endpoint put /api/bookmarks/persons/{person_id}
* @param personId
* @param createPersonBookmark
* @param secureFgpAcc
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public bookmarkPerson(personId: string, createPersonBookmark: CreatePersonBookmark, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<PersonBookmarkResponse>;
public bookmarkPerson(personId: string, createPersonBookmark: CreatePersonBookmark, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<PersonBookmarkResponse>>;
public bookmarkPerson(personId: string, createPersonBookmark: CreatePersonBookmark, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<PersonBookmarkResponse>>;
public bookmarkPerson(personId: string, createPersonBookmark: CreatePersonBookmark, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (personId === null || personId === undefined) {
throw new Error('Required parameter personId was null or undefined when calling bookmarkPerson.');
}
if (createPersonBookmark === null || createPersonBookmark === undefined) {
throw new Error('Required parameter createPersonBookmark was null or undefined when calling bookmarkPerson.');
}
let localVarHeaders = this.defaultHeaders; // authentication (HTTPBearer) required
localVarHeaders = this.configuration.addCredentialToHeaders(
'HTTPBearer',
'Authorization',
localVarHeaders,
'Bearer ',
);
// authentication (HTTPBearer) required const localVarHttpHeaderAcceptSelected: string | undefined =
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer '); options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ if (localVarHttpHeaderAcceptSelected !== undefined) {
'application/json' localVarHeaders = localVarHeaders.set(
]); 'Accept',
if (localVarHttpHeaderAcceptSelected !== undefined) { localVarHttpHeaderAcceptSelected,
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); );
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
// to determine the Content-Type header
const consumes: string[] = [
'application/json'
];
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/bookmarks/persons/${this.configuration.encodeParam({name: "personId", value: personId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<PersonBookmarkResponse>('put', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: createPersonBookmark,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
} }
/** const localVarHttpContext: HttpContext =
* List Person Bookmarks options?.context ?? new HttpContext();
* @endpoint get /api/bookmarks/persons
* @param secureFgpAcc
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public listPersonBookmarks(secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Array<PersonBookmarkResponse>>;
public listPersonBookmarks(secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Array<PersonBookmarkResponse>>>;
public listPersonBookmarks(secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Array<PersonBookmarkResponse>>>;
public listPersonBookmarks(secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
let localVarHeaders = this.defaultHeaders; const localVarTransferCache: boolean = options?.transferCache ?? true;
// authentication (HTTPBearer) required // to determine the Content-Type header
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer '); const consumes: string[] = ['application/json'];
const httpContentTypeSelected: string | undefined =
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ this.configuration.selectHeaderContentType(consumes);
'application/json' if (httpContentTypeSelected !== undefined) {
]); localVarHeaders = localVarHeaders.set(
if (localVarHttpHeaderAcceptSelected !== undefined) { 'Content-Type',
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); httpContentTypeSelected,
} );
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/bookmarks/persons`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Array<PersonBookmarkResponse>>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
} }
/** let responseType_: 'text' | 'json' | 'blob' = 'json';
* Remove Person Bookmark if (localVarHttpHeaderAcceptSelected) {
* @endpoint delete /api/bookmarks/persons/{person_id} if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
* @param personId responseType_ = 'text';
* @param secureFgpAcc } else if (
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
* @param reportProgress flag to report request and response progress. ) {
*/ responseType_ = 'json';
public removePersonBookmark(personId: string, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>; } else {
public removePersonBookmark(personId: string, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>; responseType_ = 'blob';
public removePersonBookmark(personId: string, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>; }
public removePersonBookmark(personId: string, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (personId === null || personId === undefined) {
throw new Error('Required parameter personId was null or undefined when calling removePersonBookmark.');
}
let localVarHeaders = this.defaultHeaders;
// authentication (HTTPBearer) required
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/bookmarks/persons/${this.configuration.encodeParam({name: "personId", value: personId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<any>('delete', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
} }
let localVarPath = `/api/bookmarks/persons/${this.configuration.encodeParam({ name: 'personId', value: personId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<PersonBookmarkResponse>(
'put',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: createPersonBookmark,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
/**
* List Person Bookmarks
* @endpoint get /api/bookmarks/persons
* @param secureFgpAcc
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public listPersonBookmarks(
secureFgpAcc?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<Array<PersonBookmarkResponse>>;
public listPersonBookmarks(
secureFgpAcc?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<Array<PersonBookmarkResponse>>>;
public listPersonBookmarks(
secureFgpAcc?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<Array<PersonBookmarkResponse>>>;
public listPersonBookmarks(
secureFgpAcc?: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
let localVarHeaders = this.defaultHeaders;
// authentication (HTTPBearer) required
localVarHeaders = this.configuration.addCredentialToHeaders(
'HTTPBearer',
'Authorization',
localVarHeaders,
'Bearer ',
);
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/bookmarks/persons`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Array<PersonBookmarkResponse>>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
/**
* Remove Person Bookmark
* @endpoint delete /api/bookmarks/persons/{person_id}
* @param personId
* @param secureFgpAcc
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public removePersonBookmark(
personId: string,
secureFgpAcc?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any>;
public removePersonBookmark(
personId: string,
secureFgpAcc?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<any>>;
public removePersonBookmark(
personId: string,
secureFgpAcc?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<any>>;
public removePersonBookmark(
personId: string,
secureFgpAcc?: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (personId === null || personId === undefined) {
throw new Error(
'Required parameter personId was null or undefined when calling removePersonBookmark.',
);
}
let localVarHeaders = this.defaultHeaders;
// authentication (HTTPBearer) required
localVarHeaders = this.configuration.addCredentialToHeaders(
'HTTPBearer',
'Authorization',
localVarHeaders,
'Bearer ',
);
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/bookmarks/persons/${this.configuration.encodeParam({ name: 'personId', value: personId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<any>(
'delete',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
} }
@@ -9,12 +9,18 @@
*/ */
/* tslint:disable:no-unused-variable member-ordering */ /* tslint:disable:no-unused-variable member-ordering */
import { Inject, Injectable, Optional } from '@angular/core'; import { Inject, Injectable, Optional } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams, import {
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext HttpClient,
} from '@angular/common/http'; HttpHeaders,
import { CustomHttpParameterCodec } from '../encoder'; HttpParams,
import { Observable } from 'rxjs'; HttpResponse,
HttpEvent,
HttpParameterCodec,
HttpContext,
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
// @ts-ignore // @ts-ignore
import { CompanyConnectionsAvailability } from '../model/companyConnectionsAvailability'; import { CompanyConnectionsAvailability } from '../model/companyConnectionsAvailability';
@@ -24,137 +30,249 @@ import { CompanyConnectionsResponse } from '../model/companyConnectionsResponse'
import { HTTPValidationError } from '../model/hTTPValidationError'; import { HTTPValidationError } from '../model/hTTPValidationError';
// @ts-ignore // @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration'; import { Configuration } from '../configuration';
import { BaseService } from '../api.base.service'; import { BaseService } from '../api.base.service';
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root',
}) })
export class CompanyConnectionsService extends BaseService { export class CompanyConnectionsService extends BaseService {
constructor(
protected httpClient: HttpClient,
@Optional() @Inject(BASE_PATH) basePath: string | string[],
@Optional() configuration?: Configuration,
) {
super(basePath, configuration);
}
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { /**
super(basePath, configuration); * Check whether company connections are available for an author.
* @endpoint get /api/inse-service/authors/{author_id}/company-connections/availability
* @param authorId
* @param secureFgpAcc
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getCompanyConnectionsAvailability(
authorId: string,
secureFgpAcc?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<CompanyConnectionsAvailability>;
public getCompanyConnectionsAvailability(
authorId: string,
secureFgpAcc?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<CompanyConnectionsAvailability>>;
public getCompanyConnectionsAvailability(
authorId: string,
secureFgpAcc?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<CompanyConnectionsAvailability>>;
public getCompanyConnectionsAvailability(
authorId: string,
secureFgpAcc?: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (authorId === null || authorId === undefined) {
throw new Error(
'Required parameter authorId was null or undefined when calling getCompanyConnectionsAvailability.',
);
} }
/** let localVarHeaders = this.defaultHeaders;
* Check whether company connections are available for an author.
* @endpoint get /api/inse-service/authors/{author_id}/company-connections/availability
* @param authorId
* @param secureFgpAcc
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getCompanyConnectionsAvailability(authorId: string, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<CompanyConnectionsAvailability>;
public getCompanyConnectionsAvailability(authorId: string, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<CompanyConnectionsAvailability>>;
public getCompanyConnectionsAvailability(authorId: string, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<CompanyConnectionsAvailability>>;
public getCompanyConnectionsAvailability(authorId: string, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (authorId === null || authorId === undefined) {
throw new Error('Required parameter authorId was null or undefined when calling getCompanyConnectionsAvailability.');
}
let localVarHeaders = this.defaultHeaders; // authentication (HTTPBearer) required
localVarHeaders = this.configuration.addCredentialToHeaders(
'HTTPBearer',
'Authorization',
localVarHeaders,
'Bearer ',
);
// authentication (HTTPBearer) required const localVarHttpHeaderAcceptSelected: string | undefined =
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer '); options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ if (localVarHttpHeaderAcceptSelected !== undefined) {
'application/json' localVarHeaders = localVarHeaders.set(
]); 'Accept',
if (localVarHttpHeaderAcceptSelected !== undefined) { localVarHttpHeaderAcceptSelected,
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); );
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/inse-service/authors/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/company-connections/availability`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<CompanyConnectionsAvailability>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
} }
/** const localVarHttpContext: HttpContext =
* Get possible company connections by OpenAlex author ID. options?.context ?? new HttpContext();
* @endpoint get /api/inse-service/authors/{author_id}/company-connections
* @param authorId
* @param secureFgpAcc
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getCompanyConnectionsByAuthor(authorId: string, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<CompanyConnectionsResponse>;
public getCompanyConnectionsByAuthor(authorId: string, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<CompanyConnectionsResponse>>;
public getCompanyConnectionsByAuthor(authorId: string, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<CompanyConnectionsResponse>>;
public getCompanyConnectionsByAuthor(authorId: string, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (authorId === null || authorId === undefined) {
throw new Error('Required parameter authorId was null or undefined when calling getCompanyConnectionsByAuthor.');
}
let localVarHeaders = this.defaultHeaders; const localVarTransferCache: boolean = options?.transferCache ?? true;
// authentication (HTTPBearer) required let responseType_: 'text' | 'json' | 'blob' = 'json';
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer '); if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ responseType_ = 'text';
'application/json' } else if (
]); this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
if (localVarHttpHeaderAcceptSelected !== undefined) { ) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); responseType_ = 'json';
} } else {
responseType_ = 'blob';
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); }
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/inse-service/authors/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/company-connections`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<CompanyConnectionsResponse>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
} }
let localVarPath = `/api/inse-service/authors/${this.configuration.encodeParam({ name: 'authorId', value: authorId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}/company-connections/availability`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<CompanyConnectionsAvailability>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
/**
* Get possible company connections by OpenAlex author ID.
* @endpoint get /api/inse-service/authors/{author_id}/company-connections
* @param authorId
* @param secureFgpAcc
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getCompanyConnectionsByAuthor(
authorId: string,
secureFgpAcc?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<CompanyConnectionsResponse>;
public getCompanyConnectionsByAuthor(
authorId: string,
secureFgpAcc?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<CompanyConnectionsResponse>>;
public getCompanyConnectionsByAuthor(
authorId: string,
secureFgpAcc?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<CompanyConnectionsResponse>>;
public getCompanyConnectionsByAuthor(
authorId: string,
secureFgpAcc?: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (authorId === null || authorId === undefined) {
throw new Error(
'Required parameter authorId was null or undefined when calling getCompanyConnectionsByAuthor.',
);
}
let localVarHeaders = this.defaultHeaders;
// authentication (HTTPBearer) required
localVarHeaders = this.configuration.addCredentialToHeaders(
'HTTPBearer',
'Authorization',
localVarHeaders,
'Bearer ',
);
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/inse-service/authors/${this.configuration.encodeParam({ name: 'authorId', value: authorId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}/company-connections`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<CompanyConnectionsResponse>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
} }
+221 -121
View File
@@ -9,12 +9,18 @@
*/ */
/* tslint:disable:no-unused-variable member-ordering */ /* tslint:disable:no-unused-variable member-ordering */
import { Inject, Injectable, Optional } from '@angular/core'; import { Inject, Injectable, Optional } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams, import {
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext HttpClient,
} from '@angular/common/http'; HttpHeaders,
import { CustomHttpParameterCodec } from '../encoder'; HttpParams,
import { Observable } from 'rxjs'; HttpResponse,
HttpEvent,
HttpParameterCodec,
HttpContext,
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
// @ts-ignore // @ts-ignore
import { DfgInstitutionSummaryPage } from '../model/dfgInstitutionSummaryPage'; import { DfgInstitutionSummaryPage } from '../model/dfgInstitutionSummaryPage';
@@ -22,137 +28,231 @@ import { DfgInstitutionSummaryPage } from '../model/dfgInstitutionSummaryPage';
import { HTTPValidationError } from '../model/hTTPValidationError'; import { HTTPValidationError } from '../model/hTTPValidationError';
// @ts-ignore // @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration'; import { Configuration } from '../configuration';
import { BaseService } from '../api.base.service'; import { BaseService } from '../api.base.service';
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root',
}) })
export class DFGInstitutionsService extends BaseService { export class DFGInstitutionsService extends BaseService {
constructor(
protected httpClient: HttpClient,
@Optional() @Inject(BASE_PATH) basePath: string | string[],
@Optional() configuration?: Configuration,
) {
super(basePath, configuration);
}
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { /**
super(basePath, configuration); * Returns a list of institutions based on a search term for autocomplete functionality.
* @endpoint get /api/dfg/institutions/autocomplete/selector
* @param query A search term to filter institutions by (partial matches allowed).
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getDfgInstitutionAutocompleteForSelector(
query?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<DfgInstitutionSummaryPage>;
public getDfgInstitutionAutocompleteForSelector(
query?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<DfgInstitutionSummaryPage>>;
public getDfgInstitutionAutocompleteForSelector(
query?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<DfgInstitutionSummaryPage>>;
public getDfgInstitutionAutocompleteForSelector(
query?: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>query,
'query',
);
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
} }
/** const localVarHttpContext: HttpContext =
* Returns a list of institutions based on a search term for autocomplete functionality. options?.context ?? new HttpContext();
* @endpoint get /api/dfg/institutions/autocomplete/selector
* @param query A search term to filter institutions by (partial matches allowed).
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getDfgInstitutionAutocompleteForSelector(query?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<DfgInstitutionSummaryPage>;
public getDfgInstitutionAutocompleteForSelector(query?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<DfgInstitutionSummaryPage>>;
public getDfgInstitutionAutocompleteForSelector(query?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<DfgInstitutionSummaryPage>>;
public getDfgInstitutionAutocompleteForSelector(query?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
let localVarQueryParameters = new HttpParams({encoder: this.encoder}); const localVarTransferCache: boolean = options?.transferCache ?? true;
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>query, 'query');
let localVarHeaders = this.defaultHeaders; let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ let localVarPath = `/api/dfg/institutions/autocomplete/selector`;
'application/json' const { basePath, withCredentials } = this.configuration;
]); return this.httpClient.request<DfgInstitutionSummaryPage>(
if (localVarHttpHeaderAcceptSelected !== undefined) { 'get',
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); `${basePath}${localVarPath}`,
} {
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); /**
* Returns a list of institutions based on their IDs.
const localVarTransferCache: boolean = options?.transferCache ?? true; * @endpoint get /api/dfg/institutions/ids
* @param institutionIds A list of institution IDs to retrieve.
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
let responseType_: 'text' | 'json' | 'blob' = 'json'; * @param reportProgress flag to report request and response progress.
if (localVarHttpHeaderAcceptSelected) { */
if (localVarHttpHeaderAcceptSelected.startsWith('text')) { public getDfgInstitutionsByIds(
responseType_ = 'text'; institutionIds?: Array<string>,
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { observe?: 'body',
responseType_ = 'json'; reportProgress?: boolean,
} else { options?: {
responseType_ = 'blob'; httpHeaderAccept?: 'application/json';
} context?: HttpContext;
} transferCache?: boolean;
},
let localVarPath = `/api/dfg/institutions/autocomplete/selector`; ): Observable<DfgInstitutionSummaryPage>;
const { basePath, withCredentials } = this.configuration; public getDfgInstitutionsByIds(
return this.httpClient.request<DfgInstitutionSummaryPage>('get', `${basePath}${localVarPath}`, institutionIds?: Array<string>,
{ observe?: 'response',
context: localVarHttpContext, reportProgress?: boolean,
params: localVarQueryParameters, options?: {
responseType: <any>responseType_, httpHeaderAccept?: 'application/json';
...(withCredentials ? { withCredentials } : {}), context?: HttpContext;
headers: localVarHeaders, transferCache?: boolean;
observe: observe, },
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), ): Observable<HttpResponse<DfgInstitutionSummaryPage>>;
reportProgress: reportProgress public getDfgInstitutionsByIds(
} institutionIds?: Array<string>,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<DfgInstitutionSummaryPage>>;
public getDfgInstitutionsByIds(
institutionIds?: Array<string>,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
if (institutionIds) {
institutionIds.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>element,
'institution_ids',
); );
});
} }
/** let localVarHeaders = this.defaultHeaders;
* Returns a list of institutions based on their IDs.
* @endpoint get /api/dfg/institutions/ids
* @param institutionIds A list of institution IDs to retrieve.
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getDfgInstitutionsByIds(institutionIds?: Array<string>, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<DfgInstitutionSummaryPage>;
public getDfgInstitutionsByIds(institutionIds?: Array<string>, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<DfgInstitutionSummaryPage>>;
public getDfgInstitutionsByIds(institutionIds?: Array<string>, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<DfgInstitutionSummaryPage>>;
public getDfgInstitutionsByIds(institutionIds?: Array<string>, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
let localVarQueryParameters = new HttpParams({encoder: this.encoder}); const localVarHttpHeaderAcceptSelected: string | undefined =
if (institutionIds) { options?.httpHeaderAccept ??
institutionIds.forEach((element) => { this.configuration.selectHeaderAccept(['application/json']);
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, if (localVarHttpHeaderAcceptSelected !== undefined) {
<any>element, 'institution_ids'); localVarHeaders = localVarHeaders.set(
}) 'Accept',
} localVarHttpHeaderAcceptSelected,
);
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/dfg/institutions/ids`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<DfgInstitutionSummaryPage>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
} }
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/dfg/institutions/ids`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<DfgInstitutionSummaryPage>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
} }
+221 -121
View File
@@ -9,12 +9,18 @@
*/ */
/* tslint:disable:no-unused-variable member-ordering */ /* tslint:disable:no-unused-variable member-ordering */
import { Inject, Injectable, Optional } from '@angular/core'; import { Inject, Injectable, Optional } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams, import {
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext HttpClient,
} from '@angular/common/http'; HttpHeaders,
import { CustomHttpParameterCodec } from '../encoder'; HttpParams,
import { Observable } from 'rxjs'; HttpResponse,
HttpEvent,
HttpParameterCodec,
HttpContext,
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
// @ts-ignore // @ts-ignore
import { DfgPersonSummaryPage } from '../model/dfgPersonSummaryPage'; import { DfgPersonSummaryPage } from '../model/dfgPersonSummaryPage';
@@ -22,137 +28,231 @@ import { DfgPersonSummaryPage } from '../model/dfgPersonSummaryPage';
import { HTTPValidationError } from '../model/hTTPValidationError'; import { HTTPValidationError } from '../model/hTTPValidationError';
// @ts-ignore // @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration'; import { Configuration } from '../configuration';
import { BaseService } from '../api.base.service'; import { BaseService } from '../api.base.service';
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root',
}) })
export class DFGPersonsService extends BaseService { export class DFGPersonsService extends BaseService {
constructor(
protected httpClient: HttpClient,
@Optional() @Inject(BASE_PATH) basePath: string | string[],
@Optional() configuration?: Configuration,
) {
super(basePath, configuration);
}
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { /**
super(basePath, configuration); * Returns a list of persons based on a search term for autocomplete functionality.
* @endpoint get /api/dfg/persons/autocomplete/selector
* @param query A search term to filter persons by (partial matches allowed).
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getDfgPersonAutocompleteForSelector(
query?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<DfgPersonSummaryPage>;
public getDfgPersonAutocompleteForSelector(
query?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<DfgPersonSummaryPage>>;
public getDfgPersonAutocompleteForSelector(
query?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<DfgPersonSummaryPage>>;
public getDfgPersonAutocompleteForSelector(
query?: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>query,
'query',
);
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
} }
/** const localVarHttpContext: HttpContext =
* Returns a list of persons based on a search term for autocomplete functionality. options?.context ?? new HttpContext();
* @endpoint get /api/dfg/persons/autocomplete/selector
* @param query A search term to filter persons by (partial matches allowed).
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getDfgPersonAutocompleteForSelector(query?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<DfgPersonSummaryPage>;
public getDfgPersonAutocompleteForSelector(query?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<DfgPersonSummaryPage>>;
public getDfgPersonAutocompleteForSelector(query?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<DfgPersonSummaryPage>>;
public getDfgPersonAutocompleteForSelector(query?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
let localVarQueryParameters = new HttpParams({encoder: this.encoder}); const localVarTransferCache: boolean = options?.transferCache ?? true;
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>query, 'query');
let localVarHeaders = this.defaultHeaders; let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ let localVarPath = `/api/dfg/persons/autocomplete/selector`;
'application/json' const { basePath, withCredentials } = this.configuration;
]); return this.httpClient.request<DfgPersonSummaryPage>(
if (localVarHttpHeaderAcceptSelected !== undefined) { 'get',
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); `${basePath}${localVarPath}`,
} {
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); /**
* Returns a list of persons based on their IDs.
const localVarTransferCache: boolean = options?.transferCache ?? true; * @endpoint get /api/dfg/persons/ids
* @param personIds A list of person IDs to retrieve.
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
let responseType_: 'text' | 'json' | 'blob' = 'json'; * @param reportProgress flag to report request and response progress.
if (localVarHttpHeaderAcceptSelected) { */
if (localVarHttpHeaderAcceptSelected.startsWith('text')) { public getDfgPersonsByIds(
responseType_ = 'text'; personIds?: Array<string>,
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { observe?: 'body',
responseType_ = 'json'; reportProgress?: boolean,
} else { options?: {
responseType_ = 'blob'; httpHeaderAccept?: 'application/json';
} context?: HttpContext;
} transferCache?: boolean;
},
let localVarPath = `/api/dfg/persons/autocomplete/selector`; ): Observable<DfgPersonSummaryPage>;
const { basePath, withCredentials } = this.configuration; public getDfgPersonsByIds(
return this.httpClient.request<DfgPersonSummaryPage>('get', `${basePath}${localVarPath}`, personIds?: Array<string>,
{ observe?: 'response',
context: localVarHttpContext, reportProgress?: boolean,
params: localVarQueryParameters, options?: {
responseType: <any>responseType_, httpHeaderAccept?: 'application/json';
...(withCredentials ? { withCredentials } : {}), context?: HttpContext;
headers: localVarHeaders, transferCache?: boolean;
observe: observe, },
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), ): Observable<HttpResponse<DfgPersonSummaryPage>>;
reportProgress: reportProgress public getDfgPersonsByIds(
} personIds?: Array<string>,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<DfgPersonSummaryPage>>;
public getDfgPersonsByIds(
personIds?: Array<string>,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
if (personIds) {
personIds.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>element,
'person_ids',
); );
});
} }
/** let localVarHeaders = this.defaultHeaders;
* Returns a list of persons based on their IDs.
* @endpoint get /api/dfg/persons/ids
* @param personIds A list of person IDs to retrieve.
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getDfgPersonsByIds(personIds?: Array<string>, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<DfgPersonSummaryPage>;
public getDfgPersonsByIds(personIds?: Array<string>, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<DfgPersonSummaryPage>>;
public getDfgPersonsByIds(personIds?: Array<string>, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<DfgPersonSummaryPage>>;
public getDfgPersonsByIds(personIds?: Array<string>, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
let localVarQueryParameters = new HttpParams({encoder: this.encoder}); const localVarHttpHeaderAcceptSelected: string | undefined =
if (personIds) { options?.httpHeaderAccept ??
personIds.forEach((element) => { this.configuration.selectHeaderAccept(['application/json']);
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, if (localVarHttpHeaderAcceptSelected !== undefined) {
<any>element, 'person_ids'); localVarHeaders = localVarHeaders.set(
}) 'Accept',
} localVarHttpHeaderAcceptSelected,
);
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/dfg/persons/ids`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<DfgPersonSummaryPage>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
} }
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/dfg/persons/ids`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<DfgPersonSummaryPage>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
} }
File diff suppressed because it is too large Load Diff
+239 -125
View File
@@ -9,12 +9,18 @@
*/ */
/* tslint:disable:no-unused-variable member-ordering */ /* tslint:disable:no-unused-variable member-ordering */
import { Inject, Injectable, Optional } from '@angular/core'; import { Inject, Injectable, Optional } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams, import {
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext HttpClient,
} from '@angular/common/http'; HttpHeaders,
import { CustomHttpParameterCodec } from '../encoder'; HttpParams,
import { Observable } from 'rxjs'; HttpResponse,
HttpEvent,
HttpParameterCodec,
HttpContext,
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
// @ts-ignore // @ts-ignore
import { FundersByAuthorResponse } from '../model/fundersByAuthorResponse'; import { FundersByAuthorResponse } from '../model/fundersByAuthorResponse';
@@ -24,138 +30,246 @@ import { HTTPValidationError } from '../model/hTTPValidationError';
import { PublicationsByAuthorResponse } from '../model/publicationsByAuthorResponse'; import { PublicationsByAuthorResponse } from '../model/publicationsByAuthorResponse';
// @ts-ignore // @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration'; import { Configuration } from '../configuration';
import { BaseService } from '../api.base.service'; import { BaseService } from '../api.base.service';
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root',
}) })
export class FundingService extends BaseService { export class FundingService extends BaseService {
constructor(
protected httpClient: HttpClient,
@Optional() @Inject(BASE_PATH) basePath: string | string[],
@Optional() configuration?: Configuration,
) {
super(basePath, configuration);
}
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { /**
super(basePath, configuration); * Get funding organizations by author.
* @endpoint get /api/inse-service/authors/{author_id}/funders
* @param authorId
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getFundersByAuthor(
authorId: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<FundersByAuthorResponse>;
public getFundersByAuthor(
authorId: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<FundersByAuthorResponse>>;
public getFundersByAuthor(
authorId: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<FundersByAuthorResponse>>;
public getFundersByAuthor(
authorId: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (authorId === null || authorId === undefined) {
throw new Error(
'Required parameter authorId was null or undefined when calling getFundersByAuthor.',
);
} }
/** let localVarHeaders = this.defaultHeaders;
* Get funding organizations by author.
* @endpoint get /api/inse-service/authors/{author_id}/funders
* @param authorId
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getFundersByAuthor(authorId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<FundersByAuthorResponse>;
public getFundersByAuthor(authorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<FundersByAuthorResponse>>;
public getFundersByAuthor(authorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<FundersByAuthorResponse>>;
public getFundersByAuthor(authorId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (authorId === null || authorId === undefined) {
throw new Error('Required parameter authorId was null or undefined when calling getFundersByAuthor.');
}
let localVarHeaders = this.defaultHeaders; const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ this.configuration.selectHeaderAccept(['application/json']);
'application/json' if (localVarHttpHeaderAcceptSelected !== undefined) {
]); localVarHeaders = localVarHeaders.set(
if (localVarHttpHeaderAcceptSelected !== undefined) { 'Accept',
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); localVarHttpHeaderAcceptSelected,
} );
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/inse-service/authors/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/funders`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<FundersByAuthorResponse>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
} }
/** const localVarHttpContext: HttpContext =
* Get funded publications by author. options?.context ?? new HttpContext();
* @endpoint get /api/inse-service/authors/{author_id}/publications
* @param authorId
* @param page
* @param pageSize
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getPublicationsByAuthor(authorId: string, page?: number, pageSize?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<PublicationsByAuthorResponse>;
public getPublicationsByAuthor(authorId: string, page?: number, pageSize?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<PublicationsByAuthorResponse>>;
public getPublicationsByAuthor(authorId: string, page?: number, pageSize?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<PublicationsByAuthorResponse>>;
public getPublicationsByAuthor(authorId: string, page?: number, pageSize?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (authorId === null || authorId === undefined) {
throw new Error('Required parameter authorId was null or undefined when calling getPublicationsByAuthor.');
}
let localVarQueryParameters = new HttpParams({encoder: this.encoder}); const localVarTransferCache: boolean = options?.transferCache ?? true;
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>page, 'page');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>pageSize, 'page_size');
let localVarHeaders = this.defaultHeaders; let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
'application/json' responseType_ = 'text';
]); } else if (
if (localVarHttpHeaderAcceptSelected !== undefined) { this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); ) {
} responseType_ = 'json';
} else {
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); responseType_ = 'blob';
}
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/inse-service/authors/${this.configuration.encodeParam({name: "authorId", value: authorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/publications`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<PublicationsByAuthorResponse>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
} }
let localVarPath = `/api/inse-service/authors/${this.configuration.encodeParam({ name: 'authorId', value: authorId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}/funders`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<FundersByAuthorResponse>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
/**
* Get funded publications by author.
* @endpoint get /api/inse-service/authors/{author_id}/publications
* @param authorId
* @param page
* @param pageSize
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getPublicationsByAuthor(
authorId: string,
page?: number,
pageSize?: number,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<PublicationsByAuthorResponse>;
public getPublicationsByAuthor(
authorId: string,
page?: number,
pageSize?: number,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<PublicationsByAuthorResponse>>;
public getPublicationsByAuthor(
authorId: string,
page?: number,
pageSize?: number,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<PublicationsByAuthorResponse>>;
public getPublicationsByAuthor(
authorId: string,
page?: number,
pageSize?: number,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (authorId === null || authorId === undefined) {
throw new Error(
'Required parameter authorId was null or undefined when calling getPublicationsByAuthor.',
);
}
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>page,
'page',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>pageSize,
'page_size',
);
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/inse-service/authors/${this.configuration.encodeParam({ name: 'authorId', value: authorId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}/publications`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<PublicationsByAuthorResponse>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
} }
+323 -173
View File
@@ -9,205 +9,355 @@
*/ */
/* tslint:disable:no-unused-variable member-ordering */ /* tslint:disable:no-unused-variable member-ordering */
import { Inject, Injectable, Optional } from '@angular/core'; import { Inject, Injectable, Optional } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams, import {
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext HttpClient,
} from '@angular/common/http'; HttpHeaders,
import { CustomHttpParameterCodec } from '../encoder'; HttpParams,
import { Observable } from 'rxjs'; HttpResponse,
HttpEvent,
HttpParameterCodec,
HttpContext,
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
// @ts-ignore // @ts-ignore
import { HTTPValidationError } from '../model/hTTPValidationError'; import { HTTPValidationError } from '../model/hTTPValidationError';
// @ts-ignore // @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration'; import { Configuration } from '../configuration';
import { BaseService } from '../api.base.service'; import { BaseService } from '../api.base.service';
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root',
}) })
export class INSEServiceService extends BaseService { export class INSEServiceService extends BaseService {
constructor(
protected httpClient: HttpClient,
@Optional() @Inject(BASE_PATH) basePath: string | string[],
@Optional() configuration?: Configuration,
) {
super(basePath, configuration);
}
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { /**
super(basePath, configuration); * Builds the topic hierarchy cache.
* @endpoint get /api/inse-service/topics/cache
* @param pageSize Page size for each search page.
* @param saveJson Persist cache JSON to data folder.
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public buildTopicCache(
pageSize?: number,
saveJson?: boolean,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<object>;
public buildTopicCache(
pageSize?: number,
saveJson?: boolean,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<object>>;
public buildTopicCache(
pageSize?: number,
saveJson?: boolean,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<object>>;
public buildTopicCache(
pageSize?: number,
saveJson?: boolean,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>pageSize,
'page_size',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>saveJson,
'save_json',
);
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
} }
/** const localVarHttpContext: HttpContext =
* Builds the topic hierarchy cache. options?.context ?? new HttpContext();
* @endpoint get /api/inse-service/topics/cache
* @param pageSize Page size for each search page.
* @param saveJson Persist cache JSON to data folder.
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public buildTopicCache(pageSize?: number, saveJson?: boolean, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<object>;
public buildTopicCache(pageSize?: number, saveJson?: boolean, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<object>>;
public buildTopicCache(pageSize?: number, saveJson?: boolean, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<object>>;
public buildTopicCache(pageSize?: number, saveJson?: boolean, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
let localVarQueryParameters = new HttpParams({encoder: this.encoder}); const localVarTransferCache: boolean = options?.transferCache ?? true;
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>pageSize, 'page_size');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>saveJson, 'save_json');
let localVarHeaders = this.defaultHeaders; let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ let localVarPath = `/api/inse-service/topics/cache`;
'application/json' const { basePath, withCredentials } = this.configuration;
]); return this.httpClient.request<object>(
if (localVarHttpHeaderAcceptSelected !== undefined) { 'get',
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); `${basePath}${localVarPath}`,
} {
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); /**
* Counts topic hierarchy occurrences from cache.
* @endpoint get /api/inse-service/topics/count
* @param topic Topic names (repeat parameter).
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public countTopicHierarchy(
topic: Array<string>,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<object>;
public countTopicHierarchy(
topic: Array<string>,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<object>>;
public countTopicHierarchy(
topic: Array<string>,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<object>>;
public countTopicHierarchy(
topic: Array<string>,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (topic === null || topic === undefined) {
throw new Error(
'Required parameter topic was null or undefined when calling countTopicHierarchy.',
);
}
const localVarTransferCache: boolean = options?.transferCache ?? true; let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
if (topic) {
topic.forEach((element) => {
let responseType_: 'text' | 'json' | 'blob' = 'json'; localVarQueryParameters = this.addToHttpParams(
if (localVarHttpHeaderAcceptSelected) { localVarQueryParameters,
if (localVarHttpHeaderAcceptSelected.startsWith('text')) { <any>element,
responseType_ = 'text'; 'topic',
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/inse-service/topics/cache`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<object>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
); );
});
} }
/** let localVarHeaders = this.defaultHeaders;
* Counts topic hierarchy occurrences from cache.
* @endpoint get /api/inse-service/topics/count
* @param topic Topic names (repeat parameter).
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public countTopicHierarchy(topic: Array<string>, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<object>;
public countTopicHierarchy(topic: Array<string>, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<object>>;
public countTopicHierarchy(topic: Array<string>, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<object>>;
public countTopicHierarchy(topic: Array<string>, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (topic === null || topic === undefined) {
throw new Error('Required parameter topic was null or undefined when calling countTopicHierarchy.');
}
let localVarQueryParameters = new HttpParams({encoder: this.encoder}); const localVarHttpHeaderAcceptSelected: string | undefined =
if (topic) { options?.httpHeaderAccept ??
topic.forEach((element) => { this.configuration.selectHeaderAccept(['application/json']);
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, if (localVarHttpHeaderAcceptSelected !== undefined) {
<any>element, 'topic'); localVarHeaders = localVarHeaders.set(
}) 'Accept',
} localVarHttpHeaderAcceptSelected,
);
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/inse-service/topics/count`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<object>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
} }
/** const localVarHttpContext: HttpContext =
* Returns the nested topic hierarchy (Domains -&gt; Fields -&gt; Subfields -&gt; Topics). options?.context ?? new HttpContext();
* @endpoint get /api/inse-service/topics/hierarchy
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getTopicHierarchy(observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<object>;
public getTopicHierarchy(observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<object>>;
public getTopicHierarchy(observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<object>>;
public getTopicHierarchy(observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
let localVarHeaders = this.defaultHeaders; const localVarTransferCache: boolean = options?.transferCache ?? true;
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ let responseType_: 'text' | 'json' | 'blob' = 'json';
'application/json' if (localVarHttpHeaderAcceptSelected) {
]); if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
if (localVarHttpHeaderAcceptSelected !== undefined) { responseType_ = 'text';
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); } else if (
} this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); responseType_ = 'json';
} else {
const localVarTransferCache: boolean = options?.transferCache ?? true; responseType_ = 'blob';
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/inse-service/topics/hierarchy`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<object>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
} }
let localVarPath = `/api/inse-service/topics/count`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<object>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
/**
* Returns the nested topic hierarchy (Domains -&gt; Fields -&gt; Subfields -&gt; Topics).
* @endpoint get /api/inse-service/topics/hierarchy
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getTopicHierarchy(
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<object>;
public getTopicHierarchy(
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<object>>;
public getTopicHierarchy(
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<object>>;
public getTopicHierarchy(
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/inse-service/topics/hierarchy`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<object>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
} }
+577 -275
View File
@@ -9,12 +9,18 @@
*/ */
/* tslint:disable:no-unused-variable member-ordering */ /* tslint:disable:no-unused-variable member-ordering */
import { Inject, Injectable, Optional } from '@angular/core'; import { Inject, Injectable, Optional } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams, import {
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext HttpClient,
} from '@angular/common/http'; HttpHeaders,
import { CustomHttpParameterCodec } from '../encoder'; HttpParams,
import { Observable } from 'rxjs'; HttpResponse,
HttpEvent,
HttpParameterCodec,
HttpContext,
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
// @ts-ignore // @ts-ignore
import { AutocompleteResponse } from '../model/autocompleteResponse'; import { AutocompleteResponse } from '../model/autocompleteResponse';
@@ -28,295 +34,591 @@ import { InstitutionPage } from '../model/institutionPage';
import { InstitutionsListResponse } from '../model/institutionsListResponse'; import { InstitutionsListResponse } from '../model/institutionsListResponse';
// @ts-ignore // @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration'; import { Configuration } from '../configuration';
import { BaseService } from '../api.base.service'; import { BaseService } from '../api.base.service';
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root',
}) })
export class InstitutionsService extends BaseService { export class InstitutionsService extends BaseService {
constructor(
protected httpClient: HttpClient,
@Optional() @Inject(BASE_PATH) basePath: string | string[],
@Optional() configuration?: Configuration,
) {
super(basePath, configuration);
}
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { /**
super(basePath, configuration); * Returns institution options for autocomplete inputs.
* @endpoint get /api/inse-service/institutions/autocomplete
* @param query Institution search text, for example \&#39;Duisburg Essen\&#39;.
* @param countryCode Optional ISO country code filter.
* @param type Optional institution type filter.
* @param limit Maximum number of autocomplete options.
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public autocompleteInstitutions(
query: string,
countryCode?: string,
type?: string,
limit?: number,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<AutocompleteResponse>;
public autocompleteInstitutions(
query: string,
countryCode?: string,
type?: string,
limit?: number,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<AutocompleteResponse>>;
public autocompleteInstitutions(
query: string,
countryCode?: string,
type?: string,
limit?: number,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<AutocompleteResponse>>;
public autocompleteInstitutions(
query: string,
countryCode?: string,
type?: string,
limit?: number,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (query === null || query === undefined) {
throw new Error(
'Required parameter query was null or undefined when calling autocompleteInstitutions.',
);
} }
/** let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
* Returns institution options for autocomplete inputs. localVarQueryParameters = this.addToHttpParams(
* @endpoint get /api/inse-service/institutions/autocomplete localVarQueryParameters,
* @param query Institution search text, for example \&#39;Duisburg Essen\&#39;. <any>query,
* @param countryCode Optional ISO country code filter. 'query',
* @param type Optional institution type filter. );
* @param limit Maximum number of autocomplete options. localVarQueryParameters = this.addToHttpParams(
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. localVarQueryParameters,
* @param reportProgress flag to report request and response progress. <any>countryCode,
*/ 'countryCode',
public autocompleteInstitutions(query: string, countryCode?: string, type?: string, limit?: number, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<AutocompleteResponse>; );
public autocompleteInstitutions(query: string, countryCode?: string, type?: string, limit?: number, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<AutocompleteResponse>>; localVarQueryParameters = this.addToHttpParams(
public autocompleteInstitutions(query: string, countryCode?: string, type?: string, limit?: number, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<AutocompleteResponse>>; localVarQueryParameters,
public autocompleteInstitutions(query: string, countryCode?: string, type?: string, limit?: number, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> { <any>type,
if (query === null || query === undefined) { 'type',
throw new Error('Required parameter query was null or undefined when calling autocompleteInstitutions.'); );
} localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>limit,
'limit',
);
let localVarQueryParameters = new HttpParams({encoder: this.encoder}); let localVarHeaders = this.defaultHeaders;
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>query, 'query');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>countryCode, 'countryCode');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>type, 'type');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>limit, 'limit');
let localVarHeaders = this.defaultHeaders; const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ this.configuration.selectHeaderAccept(['application/json']);
'application/json' if (localVarHttpHeaderAcceptSelected !== undefined) {
]); localVarHeaders = localVarHeaders.set(
if (localVarHttpHeaderAcceptSelected !== undefined) { 'Accept',
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); localVarHttpHeaderAcceptSelected,
} );
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/inse-service/institutions/autocomplete`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<AutocompleteResponse>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
} }
/** const localVarHttpContext: HttpContext =
* Returns a single institution by ID. options?.context ?? new HttpContext();
* Returns a single institution by its OpenAlex ID.
* @endpoint get /api/inse-service/institutions/{id}
* @param id
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getInstitutionById(id: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Institution>;
public getInstitutionById(id: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Institution>>;
public getInstitutionById(id: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Institution>>;
public getInstitutionById(id: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (id === null || id === undefined) {
throw new Error('Required parameter id was null or undefined when calling getInstitutionById.');
}
let localVarHeaders = this.defaultHeaders; const localVarTransferCache: boolean = options?.transferCache ?? true;
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ let responseType_: 'text' | 'json' | 'blob' = 'json';
'application/json' if (localVarHttpHeaderAcceptSelected) {
]); if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
if (localVarHttpHeaderAcceptSelected !== undefined) { responseType_ = 'text';
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); } else if (
} this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); responseType_ = 'json';
} else {
const localVarTransferCache: boolean = options?.transferCache ?? true; responseType_ = 'blob';
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/inse-service/institutions/${this.configuration.encodeParam({name: "id", value: id, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Institution>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
} }
/** let localVarPath = `/api/inse-service/institutions/autocomplete`;
* Returns a list of OpenAlex institutions. const { basePath, withCredentials } = this.configuration;
* @endpoint get /api/inse-service/institutions return this.httpClient.request<AutocompleteResponse>(
* @param search Full-text search, for example \&#39;Duisburg Essen\&#39;. 'get',
* @param filter OpenAlex filter, for example \&#39;country_code:DE,type:education\&#39;. `${basePath}${localVarPath}`,
* @param sort Sort field, for example \&#39;works_count:desc\&#39;. {
* @param groupBy OpenAlex group_by field, for example \&#39;country_code\&#39;. context: localVarHttpContext,
* @param perPage Results per page. params: localVarQueryParameters,
* @param page Page number. Use cursor for deep pagination. responseType: <any>responseType_,
* @param cursor Cursor pagination token. Use \&#39;*\&#39; to start. ...(withCredentials ? { withCredentials } : {}),
* @param sample Random sample size. Cannot be combined with sort or page. headers: localVarHeaders,
* @param select Comma-separated fields to return. observe: observe,
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. ...(localVarTransferCache !== undefined
* @param reportProgress flag to report request and response progress. ? { transferCache: localVarTransferCache }
*/ : {}),
public listInstitutions(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<InstitutionsListResponse>; reportProgress: reportProgress,
public listInstitutions(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<InstitutionsListResponse>>; },
public listInstitutions(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<InstitutionsListResponse>>; );
public listInstitutions(search?: string, filter?: string, sort?: string, groupBy?: string, perPage?: number, page?: number, cursor?: string, sample?: number, select?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> { }
let localVarQueryParameters = new HttpParams({encoder: this.encoder}); /**
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, * Returns a single institution by ID.
<any>search, 'search'); * Returns a single institution by its OpenAlex ID.
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, * @endpoint get /api/inse-service/institutions/{id}
<any>filter, 'filter'); * @param id
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
<any>sort, 'sort'); * @param reportProgress flag to report request and response progress.
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, */
<any>groupBy, 'group_by'); public getInstitutionById(
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, id: string,
<any>perPage, 'per_page'); observe?: 'body',
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, reportProgress?: boolean,
<any>page, 'page'); options?: {
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, httpHeaderAccept?: 'application/json';
<any>cursor, 'cursor'); context?: HttpContext;
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, transferCache?: boolean;
<any>sample, 'sample'); },
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, ): Observable<Institution>;
<any>select, 'select'); public getInstitutionById(
id: string,
let localVarHeaders = this.defaultHeaders; observe?: 'response',
reportProgress?: boolean,
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ options?: {
'application/json' httpHeaderAccept?: 'application/json';
]); context?: HttpContext;
if (localVarHttpHeaderAcceptSelected !== undefined) { transferCache?: boolean;
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); },
} ): Observable<HttpResponse<Institution>>;
public getInstitutionById(
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); id: string,
observe?: 'events',
const localVarTransferCache: boolean = options?.transferCache ?? true; reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
let responseType_: 'text' | 'json' | 'blob' = 'json'; context?: HttpContext;
if (localVarHttpHeaderAcceptSelected) { transferCache?: boolean;
if (localVarHttpHeaderAcceptSelected.startsWith('text')) { },
responseType_ = 'text'; ): Observable<HttpEvent<Institution>>;
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { public getInstitutionById(
responseType_ = 'json'; id: string,
} else { observe: any = 'body',
responseType_ = 'blob'; reportProgress: boolean = false,
} options?: {
} httpHeaderAccept?: 'application/json';
context?: HttpContext;
let localVarPath = `/api/inse-service/institutions`; transferCache?: boolean;
const { basePath, withCredentials } = this.configuration; },
return this.httpClient.request<InstitutionsListResponse>('get', `${basePath}${localVarPath}`, ): Observable<any> {
{ if (id === null || id === undefined) {
context: localVarHttpContext, throw new Error(
params: localVarQueryParameters, 'Required parameter id was null or undefined when calling getInstitutionById.',
responseType: <any>responseType_, );
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
} }
/** let localVarHeaders = this.defaultHeaders;
* Searches for institutions by name.
* Searches for institutions by name with pagination.
* @endpoint get /api/inse-service/institutions/search
* @param name Institution name to search for, for example \&#39;University of Duisburg Essen\&#39;.
* @param page Page number (0-indexed).
* @param size Number of institutions per page.
* @param sortBy Field to sort by, either \&#39;relevance\&#39;, \&#39;name\&#39;, \&#39;works_count\&#39;, or \&#39;citations_count\&#39;.
* @param sortingDirection Sorting direction, either \&#39;asc\&#39; or \&#39;desc\&#39;.
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public searchInstitutionsByName(name?: string, page?: number, size?: number, sortBy?: 'relevance' | 'name' | 'works_count' | 'citations_count', sortingDirection?: 'asc' | 'desc', observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<InstitutionPage>;
public searchInstitutionsByName(name?: string, page?: number, size?: number, sortBy?: 'relevance' | 'name' | 'works_count' | 'citations_count', sortingDirection?: 'asc' | 'desc', observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<InstitutionPage>>;
public searchInstitutionsByName(name?: string, page?: number, size?: number, sortBy?: 'relevance' | 'name' | 'works_count' | 'citations_count', sortingDirection?: 'asc' | 'desc', observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<InstitutionPage>>;
public searchInstitutionsByName(name?: string, page?: number, size?: number, sortBy?: 'relevance' | 'name' | 'works_count' | 'citations_count', sortingDirection?: 'asc' | 'desc', observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
let localVarQueryParameters = new HttpParams({encoder: this.encoder}); const localVarHttpHeaderAcceptSelected: string | undefined =
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, options?.httpHeaderAccept ??
<any>name, 'name'); this.configuration.selectHeaderAccept(['application/json']);
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, if (localVarHttpHeaderAcceptSelected !== undefined) {
<any>page, 'page'); localVarHeaders = localVarHeaders.set(
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, 'Accept',
<any>size, 'size'); localVarHttpHeaderAcceptSelected,
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, );
<any>sortBy, 'sort_by');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>sortingDirection, 'sorting_direction');
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/inse-service/institutions/search`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<InstitutionPage>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
} }
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/inse-service/institutions/${this.configuration.encodeParam({ name: 'id', value: id, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Institution>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
/**
* Returns a list of OpenAlex institutions.
* @endpoint get /api/inse-service/institutions
* @param search Full-text search, for example \&#39;Duisburg Essen\&#39;.
* @param filter OpenAlex filter, for example \&#39;country_code:DE,type:education\&#39;.
* @param sort Sort field, for example \&#39;works_count:desc\&#39;.
* @param groupBy OpenAlex group_by field, for example \&#39;country_code\&#39;.
* @param perPage Results per page.
* @param page Page number. Use cursor for deep pagination.
* @param cursor Cursor pagination token. Use \&#39;*\&#39; to start.
* @param sample Random sample size. Cannot be combined with sort or page.
* @param select Comma-separated fields to return.
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public listInstitutions(
search?: string,
filter?: string,
sort?: string,
groupBy?: string,
perPage?: number,
page?: number,
cursor?: string,
sample?: number,
select?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<InstitutionsListResponse>;
public listInstitutions(
search?: string,
filter?: string,
sort?: string,
groupBy?: string,
perPage?: number,
page?: number,
cursor?: string,
sample?: number,
select?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<InstitutionsListResponse>>;
public listInstitutions(
search?: string,
filter?: string,
sort?: string,
groupBy?: string,
perPage?: number,
page?: number,
cursor?: string,
sample?: number,
select?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<InstitutionsListResponse>>;
public listInstitutions(
search?: string,
filter?: string,
sort?: string,
groupBy?: string,
perPage?: number,
page?: number,
cursor?: string,
sample?: number,
select?: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>search,
'search',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>filter,
'filter',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>sort,
'sort',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>groupBy,
'group_by',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>perPage,
'per_page',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>page,
'page',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>cursor,
'cursor',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>sample,
'sample',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>select,
'select',
);
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/inse-service/institutions`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<InstitutionsListResponse>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
/**
* Searches for institutions by name.
* Searches for institutions by name with pagination.
* @endpoint get /api/inse-service/institutions/search
* @param name Institution name to search for, for example \&#39;University of Duisburg Essen\&#39;.
* @param page Page number (0-indexed).
* @param size Number of institutions per page.
* @param sortBy Field to sort by, either \&#39;relevance\&#39;, \&#39;name\&#39;, \&#39;works_count\&#39;, or \&#39;citations_count\&#39;.
* @param sortingDirection Sorting direction, either \&#39;asc\&#39; or \&#39;desc\&#39;.
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public searchInstitutionsByName(
name?: string,
page?: number,
size?: number,
sortBy?: 'relevance' | 'name' | 'works_count' | 'citations_count',
sortingDirection?: 'asc' | 'desc',
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<InstitutionPage>;
public searchInstitutionsByName(
name?: string,
page?: number,
size?: number,
sortBy?: 'relevance' | 'name' | 'works_count' | 'citations_count',
sortingDirection?: 'asc' | 'desc',
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<InstitutionPage>>;
public searchInstitutionsByName(
name?: string,
page?: number,
size?: number,
sortBy?: 'relevance' | 'name' | 'works_count' | 'citations_count',
sortingDirection?: 'asc' | 'desc',
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<InstitutionPage>>;
public searchInstitutionsByName(
name?: string,
page?: number,
size?: number,
sortBy?: 'relevance' | 'name' | 'works_count' | 'citations_count',
sortingDirection?: 'asc' | 'desc',
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>name,
'name',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>page,
'page',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>size,
'size',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>sortBy,
'sort_by',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>sortingDirection,
'sorting_direction',
);
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/inse-service/institutions/search`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<InstitutionPage>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
} }
+221 -121
View File
@@ -9,12 +9,18 @@
*/ */
/* tslint:disable:no-unused-variable member-ordering */ /* tslint:disable:no-unused-variable member-ordering */
import { Inject, Injectable, Optional } from '@angular/core'; import { Inject, Injectable, Optional } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams, import {
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext HttpClient,
} from '@angular/common/http'; HttpHeaders,
import { CustomHttpParameterCodec } from '../encoder'; HttpParams,
import { Observable } from 'rxjs'; HttpResponse,
HttpEvent,
HttpParameterCodec,
HttpContext,
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
// @ts-ignore // @ts-ignore
import { HTTPValidationError } from '../model/hTTPValidationError'; import { HTTPValidationError } from '../model/hTTPValidationError';
@@ -22,137 +28,231 @@ import { HTTPValidationError } from '../model/hTTPValidationError';
import { InstitutionPageV2 } from '../model/institutionPageV2'; import { InstitutionPageV2 } from '../model/institutionPageV2';
// @ts-ignore // @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration'; import { Configuration } from '../configuration';
import { BaseService } from '../api.base.service'; import { BaseService } from '../api.base.service';
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root',
}) })
export class InstitutionsV2Service extends BaseService { export class InstitutionsV2Service extends BaseService {
constructor(
protected httpClient: HttpClient,
@Optional() @Inject(BASE_PATH) basePath: string | string[],
@Optional() configuration?: Configuration,
) {
super(basePath, configuration);
}
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { /**
super(basePath, configuration); * Returns a list of institutions based on a search term for autocomplete functionality.
* @endpoint get /api/institutions/v2/autocomplete/selector
* @param query A search term to filter institutions by (partial matches allowed).
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getInstitutionAutocompleteForSelector(
query?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<InstitutionPageV2>;
public getInstitutionAutocompleteForSelector(
query?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<InstitutionPageV2>>;
public getInstitutionAutocompleteForSelector(
query?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<InstitutionPageV2>>;
public getInstitutionAutocompleteForSelector(
query?: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>query,
'query',
);
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
} }
/** const localVarHttpContext: HttpContext =
* Returns a list of institutions based on a search term for autocomplete functionality. options?.context ?? new HttpContext();
* @endpoint get /api/institutions/v2/autocomplete/selector
* @param query A search term to filter institutions by (partial matches allowed).
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getInstitutionAutocompleteForSelector(query?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<InstitutionPageV2>;
public getInstitutionAutocompleteForSelector(query?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<InstitutionPageV2>>;
public getInstitutionAutocompleteForSelector(query?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<InstitutionPageV2>>;
public getInstitutionAutocompleteForSelector(query?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
let localVarQueryParameters = new HttpParams({encoder: this.encoder}); const localVarTransferCache: boolean = options?.transferCache ?? true;
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>query, 'query');
let localVarHeaders = this.defaultHeaders; let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ let localVarPath = `/api/institutions/v2/autocomplete/selector`;
'application/json' const { basePath, withCredentials } = this.configuration;
]); return this.httpClient.request<InstitutionPageV2>(
if (localVarHttpHeaderAcceptSelected !== undefined) { 'get',
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); `${basePath}${localVarPath}`,
} {
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); /**
* Returns a list of institutions based on their IDs.
const localVarTransferCache: boolean = options?.transferCache ?? true; * @endpoint get /api/institutions/v2/ids
* @param institutionIds A list of institution IDs to retrieve.
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
let responseType_: 'text' | 'json' | 'blob' = 'json'; * @param reportProgress flag to report request and response progress.
if (localVarHttpHeaderAcceptSelected) { */
if (localVarHttpHeaderAcceptSelected.startsWith('text')) { public getInstitutionsByIds(
responseType_ = 'text'; institutionIds?: Array<string>,
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { observe?: 'body',
responseType_ = 'json'; reportProgress?: boolean,
} else { options?: {
responseType_ = 'blob'; httpHeaderAccept?: 'application/json';
} context?: HttpContext;
} transferCache?: boolean;
},
let localVarPath = `/api/institutions/v2/autocomplete/selector`; ): Observable<InstitutionPageV2>;
const { basePath, withCredentials } = this.configuration; public getInstitutionsByIds(
return this.httpClient.request<InstitutionPageV2>('get', `${basePath}${localVarPath}`, institutionIds?: Array<string>,
{ observe?: 'response',
context: localVarHttpContext, reportProgress?: boolean,
params: localVarQueryParameters, options?: {
responseType: <any>responseType_, httpHeaderAccept?: 'application/json';
...(withCredentials ? { withCredentials } : {}), context?: HttpContext;
headers: localVarHeaders, transferCache?: boolean;
observe: observe, },
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), ): Observable<HttpResponse<InstitutionPageV2>>;
reportProgress: reportProgress public getInstitutionsByIds(
} institutionIds?: Array<string>,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<InstitutionPageV2>>;
public getInstitutionsByIds(
institutionIds?: Array<string>,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
if (institutionIds) {
institutionIds.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>element,
'institution_ids',
); );
});
} }
/** let localVarHeaders = this.defaultHeaders;
* Returns a list of institutions based on their IDs.
* @endpoint get /api/institutions/v2/ids
* @param institutionIds A list of institution IDs to retrieve.
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getInstitutionsByIds(institutionIds?: Array<string>, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<InstitutionPageV2>;
public getInstitutionsByIds(institutionIds?: Array<string>, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<InstitutionPageV2>>;
public getInstitutionsByIds(institutionIds?: Array<string>, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<InstitutionPageV2>>;
public getInstitutionsByIds(institutionIds?: Array<string>, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
let localVarQueryParameters = new HttpParams({encoder: this.encoder}); const localVarHttpHeaderAcceptSelected: string | undefined =
if (institutionIds) { options?.httpHeaderAccept ??
institutionIds.forEach((element) => { this.configuration.selectHeaderAccept(['application/json']);
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, if (localVarHttpHeaderAcceptSelected !== undefined) {
<any>element, 'institution_ids'); localVarHeaders = localVarHeaders.set(
}) 'Accept',
} localVarHttpHeaderAcceptSelected,
);
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/institutions/v2/ids`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<InstitutionPageV2>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
} }
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/institutions/v2/ids`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<InstitutionPageV2>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
} }
+243 -136
View File
@@ -9,12 +9,18 @@
*/ */
/* tslint:disable:no-unused-variable member-ordering */ /* tslint:disable:no-unused-variable member-ordering */
import { Inject, Injectable, Optional } from '@angular/core'; import { Inject, Injectable, Optional } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams, import {
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext HttpClient,
} from '@angular/common/http'; HttpHeaders,
import { CustomHttpParameterCodec } from '../encoder'; HttpParams,
import { Observable } from 'rxjs'; HttpResponse,
HttpEvent,
HttpParameterCodec,
HttpContext,
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
// @ts-ignore // @ts-ignore
import { ExtractedKeywordsResponse } from '../model/extractedKeywordsResponse'; import { ExtractedKeywordsResponse } from '../model/extractedKeywordsResponse';
@@ -28,149 +34,250 @@ import { PatentsByKeywordsRequest } from '../model/patentsByKeywordsRequest';
import { PatentsByKeywordsResponse } from '../model/patentsByKeywordsResponse'; import { PatentsByKeywordsResponse } from '../model/patentsByKeywordsResponse';
// @ts-ignore // @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration'; import { Configuration } from '../configuration';
import { BaseService } from '../api.base.service'; import { BaseService } from '../api.base.service';
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root',
}) })
export class KeywordsService extends BaseService { export class KeywordsService extends BaseService {
constructor(
protected httpClient: HttpClient,
@Optional() @Inject(BASE_PATH) basePath: string | string[],
@Optional() configuration?: Configuration,
) {
super(basePath, configuration);
}
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { /**
super(basePath, configuration); * Extracts keywords from text.
* @endpoint post /api/inse-service/keywords/extract
* @param keywordsRequest
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public extractKeywords(
keywordsRequest: KeywordsRequest,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<ExtractedKeywordsResponse>;
public extractKeywords(
keywordsRequest: KeywordsRequest,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<ExtractedKeywordsResponse>>;
public extractKeywords(
keywordsRequest: KeywordsRequest,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<ExtractedKeywordsResponse>>;
public extractKeywords(
keywordsRequest: KeywordsRequest,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (keywordsRequest === null || keywordsRequest === undefined) {
throw new Error(
'Required parameter keywordsRequest was null or undefined when calling extractKeywords.',
);
} }
/** let localVarHeaders = this.defaultHeaders;
* Extracts keywords from text.
* @endpoint post /api/inse-service/keywords/extract
* @param keywordsRequest
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public extractKeywords(keywordsRequest: KeywordsRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<ExtractedKeywordsResponse>;
public extractKeywords(keywordsRequest: KeywordsRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<ExtractedKeywordsResponse>>;
public extractKeywords(keywordsRequest: KeywordsRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<ExtractedKeywordsResponse>>;
public extractKeywords(keywordsRequest: KeywordsRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (keywordsRequest === null || keywordsRequest === undefined) {
throw new Error('Required parameter keywordsRequest was null or undefined when calling extractKeywords.');
}
let localVarHeaders = this.defaultHeaders; const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ this.configuration.selectHeaderAccept(['application/json']);
'application/json' if (localVarHttpHeaderAcceptSelected !== undefined) {
]); localVarHeaders = localVarHeaders.set(
if (localVarHttpHeaderAcceptSelected !== undefined) { 'Accept',
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); localVarHttpHeaderAcceptSelected,
} );
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
// to determine the Content-Type header
const consumes: string[] = [
'application/json'
];
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/inse-service/keywords/extract`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<ExtractedKeywordsResponse>('post', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: keywordsRequest,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
} }
/** const localVarHttpContext: HttpContext =
* Find patents matching extracted OpenAlex keywords. options?.context ?? new HttpContext();
* @endpoint post /api/inse-service/keywords/patents
* @param patentsByKeywordsRequest
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getPatentsByKeywords(patentsByKeywordsRequest: PatentsByKeywordsRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<PatentsByKeywordsResponse>;
public getPatentsByKeywords(patentsByKeywordsRequest: PatentsByKeywordsRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<PatentsByKeywordsResponse>>;
public getPatentsByKeywords(patentsByKeywordsRequest: PatentsByKeywordsRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<PatentsByKeywordsResponse>>;
public getPatentsByKeywords(patentsByKeywordsRequest: PatentsByKeywordsRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (patentsByKeywordsRequest === null || patentsByKeywordsRequest === undefined) {
throw new Error('Required parameter patentsByKeywordsRequest was null or undefined when calling getPatentsByKeywords.');
}
let localVarHeaders = this.defaultHeaders; const localVarTransferCache: boolean = options?.transferCache ?? true;
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ // to determine the Content-Type header
'application/json' const consumes: string[] = ['application/json'];
]); const httpContentTypeSelected: string | undefined =
if (localVarHttpHeaderAcceptSelected !== undefined) { this.configuration.selectHeaderContentType(consumes);
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); if (httpContentTypeSelected !== undefined) {
} localVarHeaders = localVarHeaders.set(
'Content-Type',
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); httpContentTypeSelected,
);
const localVarTransferCache: boolean = options?.transferCache ?? true;
// to determine the Content-Type header
const consumes: string[] = [
'application/json'
];
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/inse-service/keywords/patents`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<PatentsByKeywordsResponse>('post', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: patentsByKeywordsRequest,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
} }
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/inse-service/keywords/extract`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<ExtractedKeywordsResponse>(
'post',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: keywordsRequest,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
/**
* Find patents matching extracted OpenAlex keywords.
* @endpoint post /api/inse-service/keywords/patents
* @param patentsByKeywordsRequest
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getPatentsByKeywords(
patentsByKeywordsRequest: PatentsByKeywordsRequest,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<PatentsByKeywordsResponse>;
public getPatentsByKeywords(
patentsByKeywordsRequest: PatentsByKeywordsRequest,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<PatentsByKeywordsResponse>>;
public getPatentsByKeywords(
patentsByKeywordsRequest: PatentsByKeywordsRequest,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<PatentsByKeywordsResponse>>;
public getPatentsByKeywords(
patentsByKeywordsRequest: PatentsByKeywordsRequest,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (
patentsByKeywordsRequest === null ||
patentsByKeywordsRequest === undefined
) {
throw new Error(
'Required parameter patentsByKeywordsRequest was null or undefined when calling getPatentsByKeywords.',
);
}
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
// to determine the Content-Type header
const consumes: string[] = ['application/json'];
const httpContentTypeSelected: string | undefined =
this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Content-Type',
httpContentTypeSelected,
);
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/inse-service/keywords/patents`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<PatentsByKeywordsResponse>(
'post',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: patentsByKeywordsRequest,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
} }
File diff suppressed because it is too large Load Diff
+532 -268
View File
@@ -9,12 +9,18 @@
*/ */
/* tslint:disable:no-unused-variable member-ordering */ /* tslint:disable:no-unused-variable member-ordering */
import { Inject, Injectable, Optional } from '@angular/core'; import { Inject, Injectable, Optional } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams, import {
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext HttpClient,
} from '@angular/common/http'; HttpHeaders,
import { CustomHttpParameterCodec } from '../encoder'; HttpParams,
import { Observable } from 'rxjs'; HttpResponse,
HttpEvent,
HttpParameterCodec,
HttpContext,
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
// @ts-ignore // @ts-ignore
import { CreateOrganizationRequest } from '../model/createOrganizationRequest'; import { CreateOrganizationRequest } from '../model/createOrganizationRequest';
@@ -28,287 +34,545 @@ import { OrganizationPage } from '../model/organizationPage';
import { UpdateOrganizationRequest } from '../model/updateOrganizationRequest'; import { UpdateOrganizationRequest } from '../model/updateOrganizationRequest';
// @ts-ignore // @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration'; import { Configuration } from '../configuration';
import { BaseService } from '../api.base.service'; import { BaseService } from '../api.base.service';
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root',
}) })
export class OrganizationService extends BaseService { export class OrganizationService extends BaseService {
constructor(
protected httpClient: HttpClient,
@Optional() @Inject(BASE_PATH) basePath: string | string[],
@Optional() configuration?: Configuration,
) {
super(basePath, configuration);
}
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { /**
super(basePath, configuration); * Create Organization
* @endpoint post /api/organizations
* @param createOrganizationRequest
* @param secureFgpAcc
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public createOrganisation(
createOrganizationRequest: CreateOrganizationRequest,
secureFgpAcc?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<InseOrganizationManagementModelOrganizationProfile>;
public createOrganisation(
createOrganizationRequest: CreateOrganizationRequest,
secureFgpAcc?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<
HttpResponse<InseOrganizationManagementModelOrganizationProfile>
>;
public createOrganisation(
createOrganizationRequest: CreateOrganizationRequest,
secureFgpAcc?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<InseOrganizationManagementModelOrganizationProfile>>;
public createOrganisation(
createOrganizationRequest: CreateOrganizationRequest,
secureFgpAcc?: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (
createOrganizationRequest === null ||
createOrganizationRequest === undefined
) {
throw new Error(
'Required parameter createOrganizationRequest was null or undefined when calling createOrganisation.',
);
} }
/** let localVarHeaders = this.defaultHeaders;
* Create Organization
* @endpoint post /api/organizations
* @param createOrganizationRequest
* @param secureFgpAcc
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<InseOrganizationManagementModelOrganizationProfile>;
public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<InseOrganizationManagementModelOrganizationProfile>>;
public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<InseOrganizationManagementModelOrganizationProfile>>;
public createOrganisation(createOrganizationRequest: CreateOrganizationRequest, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (createOrganizationRequest === null || createOrganizationRequest === undefined) {
throw new Error('Required parameter createOrganizationRequest was null or undefined when calling createOrganisation.');
}
let localVarHeaders = this.defaultHeaders; // authentication (HTTPBearer) required
localVarHeaders = this.configuration.addCredentialToHeaders(
'HTTPBearer',
'Authorization',
localVarHeaders,
'Bearer ',
);
// authentication (HTTPBearer) required const localVarHttpHeaderAcceptSelected: string | undefined =
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer '); options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ if (localVarHttpHeaderAcceptSelected !== undefined) {
'application/json' localVarHeaders = localVarHeaders.set(
]); 'Accept',
if (localVarHttpHeaderAcceptSelected !== undefined) { localVarHttpHeaderAcceptSelected,
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); );
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
// to determine the Content-Type header
const consumes: string[] = [
'application/json'
];
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/organizations`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<InseOrganizationManagementModelOrganizationProfile>('post', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: createOrganizationRequest,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
} }
/** const localVarHttpContext: HttpContext =
* Delete Organization options?.context ?? new HttpContext();
* @endpoint delete /api/organizations/{organization_id}
* @param organizationId
* @param secureFgpAcc
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public deleteOrganisation(organizationId: string, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any>;
public deleteOrganisation(organizationId: string, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<any>>;
public deleteOrganisation(organizationId: string, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<any>>;
public deleteOrganisation(organizationId: string, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (organizationId === null || organizationId === undefined) {
throw new Error('Required parameter organizationId was null or undefined when calling deleteOrganisation.');
}
let localVarHeaders = this.defaultHeaders; const localVarTransferCache: boolean = options?.transferCache ?? true;
// authentication (HTTPBearer) required // to determine the Content-Type header
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer '); const consumes: string[] = ['application/json'];
const httpContentTypeSelected: string | undefined =
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ this.configuration.selectHeaderContentType(consumes);
'application/json' if (httpContentTypeSelected !== undefined) {
]); localVarHeaders = localVarHeaders.set(
if (localVarHttpHeaderAcceptSelected !== undefined) { 'Content-Type',
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); httpContentTypeSelected,
} );
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/organizations/${this.configuration.encodeParam({name: "organizationId", value: organizationId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: "uuid"})}`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<any>('delete', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
} }
/** let responseType_: 'text' | 'json' | 'blob' = 'json';
* Get Organizations if (localVarHttpHeaderAcceptSelected) {
* @endpoint get /api/organizations if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
* @param page responseType_ = 'text';
* @param pageSize } else if (
* @param offset this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
* @param secureFgpAcc ) {
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. responseType_ = 'json';
* @param reportProgress flag to report request and response progress. } else {
*/ responseType_ = 'blob';
public getOrganisations(page?: number, pageSize?: number, offset?: number, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<OrganizationPage>; }
public getOrganisations(page?: number, pageSize?: number, offset?: number, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<OrganizationPage>>;
public getOrganisations(page?: number, pageSize?: number, offset?: number, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<OrganizationPage>>;
public getOrganisations(page?: number, pageSize?: number, offset?: number, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>page, 'page');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>pageSize, 'page_size');
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>offset, 'offset');
let localVarHeaders = this.defaultHeaders;
// authentication (HTTPBearer) required
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer ');
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/organizations`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<OrganizationPage>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
} }
/** let localVarPath = `/api/organizations`;
* Update Organization const { basePath, withCredentials } = this.configuration;
* @endpoint put /api/organizations/{organization_id} return this.httpClient.request<InseOrganizationManagementModelOrganizationProfile>(
* @param organizationId 'post',
* @param updateOrganizationRequest `${basePath}${localVarPath}`,
* @param secureFgpAcc {
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. context: localVarHttpContext,
* @param reportProgress flag to report request and response progress. body: createOrganizationRequest,
*/ responseType: <any>responseType_,
public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<InseOrganizationManagementModelOrganizationProfile>; ...(withCredentials ? { withCredentials } : {}),
public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<InseOrganizationManagementModelOrganizationProfile>>; headers: localVarHeaders,
public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<InseOrganizationManagementModelOrganizationProfile>>; observe: observe,
public updateOrganisation(organizationId: string, updateOrganizationRequest: UpdateOrganizationRequest, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> { ...(localVarTransferCache !== undefined
if (organizationId === null || organizationId === undefined) { ? { transferCache: localVarTransferCache }
throw new Error('Required parameter organizationId was null or undefined when calling updateOrganisation.'); : {}),
} reportProgress: reportProgress,
if (updateOrganizationRequest === null || updateOrganizationRequest === undefined) { },
throw new Error('Required parameter updateOrganizationRequest was null or undefined when calling updateOrganisation.'); );
} }
let localVarHeaders = this.defaultHeaders; /**
* Delete Organization
// authentication (HTTPBearer) required * @endpoint delete /api/organizations/{organization_id}
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer '); * @param organizationId
* @param secureFgpAcc
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
'application/json' * @param reportProgress flag to report request and response progress.
]); */
if (localVarHttpHeaderAcceptSelected !== undefined) { public deleteOrganisation(
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); organizationId: string,
} secureFgpAcc?: string,
observe?: 'body',
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); reportProgress?: boolean,
options?: {
const localVarTransferCache: boolean = options?.transferCache ?? true; httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
// to determine the Content-Type header },
const consumes: string[] = [ ): Observable<any>;
'application/json' public deleteOrganisation(
]; organizationId: string,
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); secureFgpAcc?: string,
if (httpContentTypeSelected !== undefined) { observe?: 'response',
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); reportProgress?: boolean,
} options?: {
httpHeaderAccept?: 'application/json';
let responseType_: 'text' | 'json' | 'blob' = 'json'; context?: HttpContext;
if (localVarHttpHeaderAcceptSelected) { transferCache?: boolean;
if (localVarHttpHeaderAcceptSelected.startsWith('text')) { },
responseType_ = 'text'; ): Observable<HttpResponse<any>>;
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { public deleteOrganisation(
responseType_ = 'json'; organizationId: string,
} else { secureFgpAcc?: string,
responseType_ = 'blob'; observe?: 'events',
} reportProgress?: boolean,
} options?: {
httpHeaderAccept?: 'application/json';
let localVarPath = `/api/organizations/${this.configuration.encodeParam({name: "organizationId", value: organizationId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: "uuid"})}`; context?: HttpContext;
const { basePath, withCredentials } = this.configuration; transferCache?: boolean;
return this.httpClient.request<InseOrganizationManagementModelOrganizationProfile>('put', `${basePath}${localVarPath}`, },
{ ): Observable<HttpEvent<any>>;
context: localVarHttpContext, public deleteOrganisation(
body: updateOrganizationRequest, organizationId: string,
responseType: <any>responseType_, secureFgpAcc?: string,
...(withCredentials ? { withCredentials } : {}), observe: any = 'body',
headers: localVarHeaders, reportProgress: boolean = false,
observe: observe, options?: {
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), httpHeaderAccept?: 'application/json';
reportProgress: reportProgress context?: HttpContext;
} transferCache?: boolean;
); },
): Observable<any> {
if (organizationId === null || organizationId === undefined) {
throw new Error(
'Required parameter organizationId was null or undefined when calling deleteOrganisation.',
);
} }
let localVarHeaders = this.defaultHeaders;
// authentication (HTTPBearer) required
localVarHeaders = this.configuration.addCredentialToHeaders(
'HTTPBearer',
'Authorization',
localVarHeaders,
'Bearer ',
);
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/organizations/${this.configuration.encodeParam({ name: 'organizationId', value: organizationId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: 'uuid' })}`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<any>(
'delete',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
/**
* Get Organizations
* @endpoint get /api/organizations
* @param page
* @param pageSize
* @param offset
* @param secureFgpAcc
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getOrganisations(
page?: number,
pageSize?: number,
offset?: number,
secureFgpAcc?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<OrganizationPage>;
public getOrganisations(
page?: number,
pageSize?: number,
offset?: number,
secureFgpAcc?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<OrganizationPage>>;
public getOrganisations(
page?: number,
pageSize?: number,
offset?: number,
secureFgpAcc?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<OrganizationPage>>;
public getOrganisations(
page?: number,
pageSize?: number,
offset?: number,
secureFgpAcc?: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>page,
'page',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>pageSize,
'page_size',
);
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>offset,
'offset',
);
let localVarHeaders = this.defaultHeaders;
// authentication (HTTPBearer) required
localVarHeaders = this.configuration.addCredentialToHeaders(
'HTTPBearer',
'Authorization',
localVarHeaders,
'Bearer ',
);
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/organizations`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<OrganizationPage>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
/**
* Update Organization
* @endpoint put /api/organizations/{organization_id}
* @param organizationId
* @param updateOrganizationRequest
* @param secureFgpAcc
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public updateOrganisation(
organizationId: string,
updateOrganizationRequest: UpdateOrganizationRequest,
secureFgpAcc?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<InseOrganizationManagementModelOrganizationProfile>;
public updateOrganisation(
organizationId: string,
updateOrganizationRequest: UpdateOrganizationRequest,
secureFgpAcc?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<
HttpResponse<InseOrganizationManagementModelOrganizationProfile>
>;
public updateOrganisation(
organizationId: string,
updateOrganizationRequest: UpdateOrganizationRequest,
secureFgpAcc?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<InseOrganizationManagementModelOrganizationProfile>>;
public updateOrganisation(
organizationId: string,
updateOrganizationRequest: UpdateOrganizationRequest,
secureFgpAcc?: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (organizationId === null || organizationId === undefined) {
throw new Error(
'Required parameter organizationId was null or undefined when calling updateOrganisation.',
);
}
if (
updateOrganizationRequest === null ||
updateOrganizationRequest === undefined
) {
throw new Error(
'Required parameter updateOrganizationRequest was null or undefined when calling updateOrganisation.',
);
}
let localVarHeaders = this.defaultHeaders;
// authentication (HTTPBearer) required
localVarHeaders = this.configuration.addCredentialToHeaders(
'HTTPBearer',
'Authorization',
localVarHeaders,
'Bearer ',
);
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
// to determine the Content-Type header
const consumes: string[] = ['application/json'];
const httpContentTypeSelected: string | undefined =
this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Content-Type',
httpContentTypeSelected,
);
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/organizations/${this.configuration.encodeParam({ name: 'organizationId', value: organizationId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: 'uuid' })}`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<InseOrganizationManagementModelOrganizationProfile>(
'put',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: updateOrganizationRequest,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
} }
File diff suppressed because it is too large Load Diff
+136 -77
View File
@@ -9,12 +9,18 @@
*/ */
/* tslint:disable:no-unused-variable member-ordering */ /* tslint:disable:no-unused-variable member-ordering */
import { Inject, Injectable, Optional } from '@angular/core'; import { Inject, Injectable, Optional } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams, import {
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext HttpClient,
} from '@angular/common/http'; HttpHeaders,
import { CustomHttpParameterCodec } from '../encoder'; HttpParams,
import { Observable } from 'rxjs'; HttpResponse,
HttpEvent,
HttpParameterCodec,
HttpContext,
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
// @ts-ignore // @ts-ignore
import { CollaborationNetwork } from '../model/collaborationNetwork'; import { CollaborationNetwork } from '../model/collaborationNetwork';
@@ -24,86 +30,139 @@ import { FilterProperties } from '../model/filterProperties';
import { HTTPValidationError } from '../model/hTTPValidationError'; import { HTTPValidationError } from '../model/hTTPValidationError';
// @ts-ignore // @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration'; import { Configuration } from '../configuration';
import { BaseService } from '../api.base.service'; import { BaseService } from '../api.base.service';
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root',
}) })
export class PersonNetworkService extends BaseService { export class PersonNetworkService extends BaseService {
constructor(
protected httpClient: HttpClient,
@Optional() @Inject(BASE_PATH) basePath: string | string[],
@Optional() configuration?: Configuration,
) {
super(basePath, configuration);
}
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { /**
super(basePath, configuration); * Get a person\&#39;s collaboration network.
* Returns a person\&#39;s collaboration network based on their works and co-authors.
* @endpoint post /api/person/network/{raw_user_id}
* @param rawUserId The raw user ID of the person.
* @param filterProperties
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getCollaborationNetwork(
rawUserId: string,
filterProperties?: FilterProperties,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<CollaborationNetwork>;
public getCollaborationNetwork(
rawUserId: string,
filterProperties?: FilterProperties,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<CollaborationNetwork>>;
public getCollaborationNetwork(
rawUserId: string,
filterProperties?: FilterProperties,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<CollaborationNetwork>>;
public getCollaborationNetwork(
rawUserId: string,
filterProperties?: FilterProperties,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (rawUserId === null || rawUserId === undefined) {
throw new Error(
'Required parameter rawUserId was null or undefined when calling getCollaborationNetwork.',
);
} }
/** let localVarHeaders = this.defaultHeaders;
* Get a person\&#39;s collaboration network.
* Returns a person\&#39;s collaboration network based on their works and co-authors.
* @endpoint post /api/person/network/{raw_user_id}
* @param rawUserId The raw user ID of the person.
* @param filterProperties
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getCollaborationNetwork(rawUserId: string, filterProperties?: FilterProperties, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<CollaborationNetwork>;
public getCollaborationNetwork(rawUserId: string, filterProperties?: FilterProperties, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<CollaborationNetwork>>;
public getCollaborationNetwork(rawUserId: string, filterProperties?: FilterProperties, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<CollaborationNetwork>>;
public getCollaborationNetwork(rawUserId: string, filterProperties?: FilterProperties, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (rawUserId === null || rawUserId === undefined) {
throw new Error('Required parameter rawUserId was null or undefined when calling getCollaborationNetwork.');
}
let localVarHeaders = this.defaultHeaders; const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ this.configuration.selectHeaderAccept(['application/json']);
'application/json' if (localVarHttpHeaderAcceptSelected !== undefined) {
]); localVarHeaders = localVarHeaders.set(
if (localVarHttpHeaderAcceptSelected !== undefined) { 'Accept',
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); localVarHttpHeaderAcceptSelected,
} );
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
// to determine the Content-Type header
const consumes: string[] = [
'application/json'
];
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/person/network/${this.configuration.encodeParam({name: "rawUserId", value: rawUserId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<CollaborationNetwork>('post', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: filterProperties,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
} }
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
// to determine the Content-Type header
const consumes: string[] = ['application/json'];
const httpContentTypeSelected: string | undefined =
this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Content-Type',
httpContentTypeSelected,
);
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/person/network/${this.configuration.encodeParam({ name: 'rawUserId', value: rawUserId, in: 'path', style: 'simple', explode: false, dataType: 'string', dataFormat: undefined })}`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<CollaborationNetwork>(
'post',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: filterProperties,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
} }
File diff suppressed because it is too large Load Diff
+484 -264
View File
@@ -9,12 +9,18 @@
*/ */
/* tslint:disable:no-unused-variable member-ordering */ /* tslint:disable:no-unused-variable member-ordering */
import { Inject, Injectable, Optional } from '@angular/core'; import { Inject, Injectable, Optional } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams, import {
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext HttpClient,
} from '@angular/common/http'; HttpHeaders,
import { CustomHttpParameterCodec } from '../encoder'; HttpParams,
import { Observable } from 'rxjs'; HttpResponse,
HttpEvent,
HttpParameterCodec,
HttpContext,
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
// @ts-ignore // @ts-ignore
import { AuthorMetricsRequest } from '../model/authorMetricsRequest'; import { AuthorMetricsRequest } from '../model/authorMetricsRequest';
@@ -34,283 +40,497 @@ import { RankedAuthor } from '../model/rankedAuthor';
import { SelectedAuthorsRequest } from '../model/selectedAuthorsRequest'; import { SelectedAuthorsRequest } from '../model/selectedAuthorsRequest';
// @ts-ignore // @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration'; import { Configuration } from '../configuration';
import { BaseService } from '../api.base.service'; import { BaseService } from '../api.base.service';
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root',
}) })
export class RankingService extends BaseService { export class RankingService extends BaseService {
constructor(
protected httpClient: HttpClient,
@Optional() @Inject(BASE_PATH) basePath: string | string[],
@Optional() configuration?: Configuration,
) {
super(basePath, configuration);
}
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { /**
super(basePath, configuration); * Rank Author
* @endpoint post /api/rank/rank-author
* @param keywordToAuthorRequest
* @param secureFgpAcc
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public rankAuthorApiRankRankAuthorPost(
keywordToAuthorRequest: KeywordToAuthorRequest,
secureFgpAcc?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<Array<RankedAuthor>>;
public rankAuthorApiRankRankAuthorPost(
keywordToAuthorRequest: KeywordToAuthorRequest,
secureFgpAcc?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<Array<RankedAuthor>>>;
public rankAuthorApiRankRankAuthorPost(
keywordToAuthorRequest: KeywordToAuthorRequest,
secureFgpAcc?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<Array<RankedAuthor>>>;
public rankAuthorApiRankRankAuthorPost(
keywordToAuthorRequest: KeywordToAuthorRequest,
secureFgpAcc?: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (
keywordToAuthorRequest === null ||
keywordToAuthorRequest === undefined
) {
throw new Error(
'Required parameter keywordToAuthorRequest was null or undefined when calling rankAuthorApiRankRankAuthorPost.',
);
} }
/** let localVarHeaders = this.defaultHeaders;
* Rank Author
* @endpoint post /api/rank/rank-author
* @param keywordToAuthorRequest
* @param secureFgpAcc
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public rankAuthorApiRankRankAuthorPost(keywordToAuthorRequest: KeywordToAuthorRequest, secureFgpAcc?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Array<RankedAuthor>>;
public rankAuthorApiRankRankAuthorPost(keywordToAuthorRequest: KeywordToAuthorRequest, secureFgpAcc?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Array<RankedAuthor>>>;
public rankAuthorApiRankRankAuthorPost(keywordToAuthorRequest: KeywordToAuthorRequest, secureFgpAcc?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Array<RankedAuthor>>>;
public rankAuthorApiRankRankAuthorPost(keywordToAuthorRequest: KeywordToAuthorRequest, secureFgpAcc?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (keywordToAuthorRequest === null || keywordToAuthorRequest === undefined) {
throw new Error('Required parameter keywordToAuthorRequest was null or undefined when calling rankAuthorApiRankRankAuthorPost.');
}
let localVarHeaders = this.defaultHeaders; // authentication (HTTPBearer) required
localVarHeaders = this.configuration.addCredentialToHeaders(
'HTTPBearer',
'Authorization',
localVarHeaders,
'Bearer ',
);
// authentication (HTTPBearer) required const localVarHttpHeaderAcceptSelected: string | undefined =
localVarHeaders = this.configuration.addCredentialToHeaders('HTTPBearer', 'Authorization', localVarHeaders, 'Bearer '); options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ if (localVarHttpHeaderAcceptSelected !== undefined) {
'application/json' localVarHeaders = localVarHeaders.set(
]); 'Accept',
if (localVarHttpHeaderAcceptSelected !== undefined) { localVarHttpHeaderAcceptSelected,
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); );
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
// to determine the Content-Type header
const consumes: string[] = [
'application/json'
];
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/rank/rank-author`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Array<RankedAuthor>>('post', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: keywordToAuthorRequest,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
} }
/** const localVarHttpContext: HttpContext =
* Static Stats options?.context ?? new HttpContext();
* @endpoint post /api/rank/static-stats
* @param authorMetricsRequest
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public staticStatsApiRankStaticStatsPost(authorMetricsRequest: AuthorMetricsRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Array<AuthorStaticStats>>;
public staticStatsApiRankStaticStatsPost(authorMetricsRequest: AuthorMetricsRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Array<AuthorStaticStats>>>;
public staticStatsApiRankStaticStatsPost(authorMetricsRequest: AuthorMetricsRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Array<AuthorStaticStats>>>;
public staticStatsApiRankStaticStatsPost(authorMetricsRequest: AuthorMetricsRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
if (authorMetricsRequest === null || authorMetricsRequest === undefined) {
throw new Error('Required parameter authorMetricsRequest was null or undefined when calling staticStatsApiRankStaticStatsPost.');
}
let localVarHeaders = this.defaultHeaders; const localVarTransferCache: boolean = options?.transferCache ?? true;
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ // to determine the Content-Type header
'application/json' const consumes: string[] = ['application/json'];
]); const httpContentTypeSelected: string | undefined =
if (localVarHttpHeaderAcceptSelected !== undefined) { this.configuration.selectHeaderContentType(consumes);
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); if (httpContentTypeSelected !== undefined) {
} localVarHeaders = localVarHeaders.set(
'Content-Type',
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); httpContentTypeSelected,
);
const localVarTransferCache: boolean = options?.transferCache ?? true;
// to determine the Content-Type header
const consumes: string[] = [
'application/json'
];
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/rank/static-stats`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Array<AuthorStaticStats>>('post', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: authorMetricsRequest,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
} }
/** let responseType_: 'text' | 'json' | 'blob' = 'json';
* Topic Profile if (localVarHttpHeaderAcceptSelected) {
* @endpoint post /api/rank/topic-profile if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
* @param selectedAuthorsRequest responseType_ = 'text';
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. } else if (
* @param reportProgress flag to report request and response progress. this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
*/ ) {
public topicProfileApiRankTopicProfilePost(selectedAuthorsRequest: SelectedAuthorsRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Array<AuthorTopicProfile>>; responseType_ = 'json';
public topicProfileApiRankTopicProfilePost(selectedAuthorsRequest: SelectedAuthorsRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Array<AuthorTopicProfile>>>; } else {
public topicProfileApiRankTopicProfilePost(selectedAuthorsRequest: SelectedAuthorsRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Array<AuthorTopicProfile>>>; responseType_ = 'blob';
public topicProfileApiRankTopicProfilePost(selectedAuthorsRequest: SelectedAuthorsRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> { }
if (selectedAuthorsRequest === null || selectedAuthorsRequest === undefined) {
throw new Error('Required parameter selectedAuthorsRequest was null or undefined when calling topicProfileApiRankTopicProfilePost.');
}
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
// to determine the Content-Type header
const consumes: string[] = [
'application/json'
];
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected);
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/rank/topic-profile`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Array<AuthorTopicProfile>>('post', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: selectedAuthorsRequest,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
} }
/** let localVarPath = `/api/rank/rank-author`;
* Topic Stats const { basePath, withCredentials } = this.configuration;
* @endpoint post /api/rank/topic-stats return this.httpClient.request<Array<RankedAuthor>>(
* @param selectedAuthorsRequest 'post',
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body. `${basePath}${localVarPath}`,
* @param reportProgress flag to report request and response progress. {
*/ context: localVarHttpContext,
public topicStatsApiRankTopicStatsPost(selectedAuthorsRequest: SelectedAuthorsRequest, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Array<AuthorTopicStats>>; body: keywordToAuthorRequest,
public topicStatsApiRankTopicStatsPost(selectedAuthorsRequest: SelectedAuthorsRequest, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Array<AuthorTopicStats>>>; responseType: <any>responseType_,
public topicStatsApiRankTopicStatsPost(selectedAuthorsRequest: SelectedAuthorsRequest, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Array<AuthorTopicStats>>>; ...(withCredentials ? { withCredentials } : {}),
public topicStatsApiRankTopicStatsPost(selectedAuthorsRequest: SelectedAuthorsRequest, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> { headers: localVarHeaders,
if (selectedAuthorsRequest === null || selectedAuthorsRequest === undefined) { observe: observe,
throw new Error('Required parameter selectedAuthorsRequest was null or undefined when calling topicStatsApiRankTopicStatsPost.'); ...(localVarTransferCache !== undefined
} ? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
let localVarHeaders = this.defaultHeaders; /**
* Static Stats
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ * @endpoint post /api/rank/static-stats
'application/json' * @param authorMetricsRequest
]); * @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
if (localVarHttpHeaderAcceptSelected !== undefined) { * @param reportProgress flag to report request and response progress.
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); */
} public staticStatsApiRankStaticStatsPost(
authorMetricsRequest: AuthorMetricsRequest,
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); observe?: 'body',
reportProgress?: boolean,
const localVarTransferCache: boolean = options?.transferCache ?? true; options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
// to determine the Content-Type header transferCache?: boolean;
const consumes: string[] = [ },
'application/json' ): Observable<Array<AuthorStaticStats>>;
]; public staticStatsApiRankStaticStatsPost(
const httpContentTypeSelected: string | undefined = this.configuration.selectHeaderContentType(consumes); authorMetricsRequest: AuthorMetricsRequest,
if (httpContentTypeSelected !== undefined) { observe?: 'response',
localVarHeaders = localVarHeaders.set('Content-Type', httpContentTypeSelected); reportProgress?: boolean,
} options?: {
httpHeaderAccept?: 'application/json';
let responseType_: 'text' | 'json' | 'blob' = 'json'; context?: HttpContext;
if (localVarHttpHeaderAcceptSelected) { transferCache?: boolean;
if (localVarHttpHeaderAcceptSelected.startsWith('text')) { },
responseType_ = 'text'; ): Observable<HttpResponse<Array<AuthorStaticStats>>>;
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { public staticStatsApiRankStaticStatsPost(
responseType_ = 'json'; authorMetricsRequest: AuthorMetricsRequest,
} else { observe?: 'events',
responseType_ = 'blob'; reportProgress?: boolean,
} options?: {
} httpHeaderAccept?: 'application/json';
context?: HttpContext;
let localVarPath = `/api/rank/topic-stats`; transferCache?: boolean;
const { basePath, withCredentials } = this.configuration; },
return this.httpClient.request<Array<AuthorTopicStats>>('post', `${basePath}${localVarPath}`, ): Observable<HttpEvent<Array<AuthorStaticStats>>>;
{ public staticStatsApiRankStaticStatsPost(
context: localVarHttpContext, authorMetricsRequest: AuthorMetricsRequest,
body: selectedAuthorsRequest, observe: any = 'body',
responseType: <any>responseType_, reportProgress: boolean = false,
...(withCredentials ? { withCredentials } : {}), options?: {
headers: localVarHeaders, httpHeaderAccept?: 'application/json';
observe: observe, context?: HttpContext;
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), transferCache?: boolean;
reportProgress: reportProgress },
} ): Observable<any> {
); if (authorMetricsRequest === null || authorMetricsRequest === undefined) {
throw new Error(
'Required parameter authorMetricsRequest was null or undefined when calling staticStatsApiRankStaticStatsPost.',
);
} }
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
// to determine the Content-Type header
const consumes: string[] = ['application/json'];
const httpContentTypeSelected: string | undefined =
this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Content-Type',
httpContentTypeSelected,
);
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/rank/static-stats`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Array<AuthorStaticStats>>(
'post',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: authorMetricsRequest,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
/**
* Topic Profile
* @endpoint post /api/rank/topic-profile
* @param selectedAuthorsRequest
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public topicProfileApiRankTopicProfilePost(
selectedAuthorsRequest: SelectedAuthorsRequest,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<Array<AuthorTopicProfile>>;
public topicProfileApiRankTopicProfilePost(
selectedAuthorsRequest: SelectedAuthorsRequest,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<Array<AuthorTopicProfile>>>;
public topicProfileApiRankTopicProfilePost(
selectedAuthorsRequest: SelectedAuthorsRequest,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<Array<AuthorTopicProfile>>>;
public topicProfileApiRankTopicProfilePost(
selectedAuthorsRequest: SelectedAuthorsRequest,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (
selectedAuthorsRequest === null ||
selectedAuthorsRequest === undefined
) {
throw new Error(
'Required parameter selectedAuthorsRequest was null or undefined when calling topicProfileApiRankTopicProfilePost.',
);
}
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
// to determine the Content-Type header
const consumes: string[] = ['application/json'];
const httpContentTypeSelected: string | undefined =
this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Content-Type',
httpContentTypeSelected,
);
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/rank/topic-profile`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Array<AuthorTopicProfile>>(
'post',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: selectedAuthorsRequest,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
/**
* Topic Stats
* @endpoint post /api/rank/topic-stats
* @param selectedAuthorsRequest
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public topicStatsApiRankTopicStatsPost(
selectedAuthorsRequest: SelectedAuthorsRequest,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<Array<AuthorTopicStats>>;
public topicStatsApiRankTopicStatsPost(
selectedAuthorsRequest: SelectedAuthorsRequest,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<Array<AuthorTopicStats>>>;
public topicStatsApiRankTopicStatsPost(
selectedAuthorsRequest: SelectedAuthorsRequest,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<Array<AuthorTopicStats>>>;
public topicStatsApiRankTopicStatsPost(
selectedAuthorsRequest: SelectedAuthorsRequest,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
if (
selectedAuthorsRequest === null ||
selectedAuthorsRequest === undefined
) {
throw new Error(
'Required parameter selectedAuthorsRequest was null or undefined when calling topicStatsApiRankTopicStatsPost.',
);
}
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
}
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
// to determine the Content-Type header
const consumes: string[] = ['application/json'];
const httpContentTypeSelected: string | undefined =
this.configuration.selectHeaderContentType(consumes);
if (httpContentTypeSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Content-Type',
httpContentTypeSelected,
);
}
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/rank/topic-stats`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<Array<AuthorTopicStats>>(
'post',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
body: selectedAuthorsRequest,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
} }
File diff suppressed because it is too large Load Diff
+221 -121
View File
@@ -9,12 +9,18 @@
*/ */
/* tslint:disable:no-unused-variable member-ordering */ /* tslint:disable:no-unused-variable member-ordering */
import { Inject, Injectable, Optional } from '@angular/core'; import { Inject, Injectable, Optional } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams, import {
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext HttpClient,
} from '@angular/common/http'; HttpHeaders,
import { CustomHttpParameterCodec } from '../encoder'; HttpParams,
import { Observable } from 'rxjs'; HttpResponse,
HttpEvent,
HttpParameterCodec,
HttpContext,
} from '@angular/common/http';
import { CustomHttpParameterCodec } from '../encoder';
import { Observable } from 'rxjs';
// @ts-ignore // @ts-ignore
import { HTTPValidationError } from '../model/hTTPValidationError'; import { HTTPValidationError } from '../model/hTTPValidationError';
@@ -22,137 +28,231 @@ import { HTTPValidationError } from '../model/hTTPValidationError';
import { TopicPageV2 } from '../model/topicPageV2'; import { TopicPageV2 } from '../model/topicPageV2';
// @ts-ignore // @ts-ignore
import { BASE_PATH, COLLECTION_FORMATS } from '../variables'; import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
import { Configuration } from '../configuration'; import { Configuration } from '../configuration';
import { BaseService } from '../api.base.service'; import { BaseService } from '../api.base.service';
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root',
}) })
export class TopicsV2Service extends BaseService { export class TopicsV2Service extends BaseService {
constructor(
protected httpClient: HttpClient,
@Optional() @Inject(BASE_PATH) basePath: string | string[],
@Optional() configuration?: Configuration,
) {
super(basePath, configuration);
}
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) { /**
super(basePath, configuration); * Returns a paginated list of topics for a given search term based on their display name.
* @endpoint get /api/topics/v2/autocomplete/selector
* @param query A search term to filter topics by (partial matches allowed).
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public autocompleteTopicsForSelector(
query?: string,
observe?: 'body',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<TopicPageV2>;
public autocompleteTopicsForSelector(
query?: string,
observe?: 'response',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpResponse<TopicPageV2>>;
public autocompleteTopicsForSelector(
query?: string,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<TopicPageV2>>;
public autocompleteTopicsForSelector(
query?: string,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>query,
'query',
);
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined =
options?.httpHeaderAccept ??
this.configuration.selectHeaderAccept(['application/json']);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set(
'Accept',
localVarHttpHeaderAcceptSelected,
);
} }
/** const localVarHttpContext: HttpContext =
* Returns a paginated list of topics for a given search term based on their display name. options?.context ?? new HttpContext();
* @endpoint get /api/topics/v2/autocomplete/selector
* @param query A search term to filter topics by (partial matches allowed).
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public autocompleteTopicsForSelector(query?: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<TopicPageV2>;
public autocompleteTopicsForSelector(query?: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<TopicPageV2>>;
public autocompleteTopicsForSelector(query?: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<TopicPageV2>>;
public autocompleteTopicsForSelector(query?: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
let localVarQueryParameters = new HttpParams({encoder: this.encoder}); const localVarTransferCache: boolean = options?.transferCache ?? true;
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
<any>query, 'query');
let localVarHeaders = this.defaultHeaders; let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([ let localVarPath = `/api/topics/v2/autocomplete/selector`;
'application/json' const { basePath, withCredentials } = this.configuration;
]); return this.httpClient.request<TopicPageV2>(
if (localVarHttpHeaderAcceptSelected !== undefined) { 'get',
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected); `${basePath}${localVarPath}`,
} {
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext(); /**
* Returns a paginated list of topics for a given list of topic IDs.
const localVarTransferCache: boolean = options?.transferCache ?? true; * @endpoint get /api/topics/v2/topics/id
* @param topicIds A list of topic IDs to retrieve.
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
let responseType_: 'text' | 'json' | 'blob' = 'json'; * @param reportProgress flag to report request and response progress.
if (localVarHttpHeaderAcceptSelected) { */
if (localVarHttpHeaderAcceptSelected.startsWith('text')) { public getTopicsByIds(
responseType_ = 'text'; topicIds?: Array<string>,
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) { observe?: 'body',
responseType_ = 'json'; reportProgress?: boolean,
} else { options?: {
responseType_ = 'blob'; httpHeaderAccept?: 'application/json';
} context?: HttpContext;
} transferCache?: boolean;
},
let localVarPath = `/api/topics/v2/autocomplete/selector`; ): Observable<TopicPageV2>;
const { basePath, withCredentials } = this.configuration; public getTopicsByIds(
return this.httpClient.request<TopicPageV2>('get', `${basePath}${localVarPath}`, topicIds?: Array<string>,
{ observe?: 'response',
context: localVarHttpContext, reportProgress?: boolean,
params: localVarQueryParameters, options?: {
responseType: <any>responseType_, httpHeaderAccept?: 'application/json';
...(withCredentials ? { withCredentials } : {}), context?: HttpContext;
headers: localVarHeaders, transferCache?: boolean;
observe: observe, },
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}), ): Observable<HttpResponse<TopicPageV2>>;
reportProgress: reportProgress public getTopicsByIds(
} topicIds?: Array<string>,
observe?: 'events',
reportProgress?: boolean,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<HttpEvent<TopicPageV2>>;
public getTopicsByIds(
topicIds?: Array<string>,
observe: any = 'body',
reportProgress: boolean = false,
options?: {
httpHeaderAccept?: 'application/json';
context?: HttpContext;
transferCache?: boolean;
},
): Observable<any> {
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
if (topicIds) {
topicIds.forEach((element) => {
localVarQueryParameters = this.addToHttpParams(
localVarQueryParameters,
<any>element,
'topic_ids',
); );
});
} }
/** let localVarHeaders = this.defaultHeaders;
* Returns a paginated list of topics for a given list of topic IDs.
* @endpoint get /api/topics/v2/topics/id
* @param topicIds A list of topic IDs to retrieve.
* @param observe set whether or not to return the data Observable as the body, response or events. defaults to returning the body.
* @param reportProgress flag to report request and response progress.
*/
public getTopicsByIds(topicIds?: Array<string>, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<TopicPageV2>;
public getTopicsByIds(topicIds?: Array<string>, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<TopicPageV2>>;
public getTopicsByIds(topicIds?: Array<string>, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<TopicPageV2>>;
public getTopicsByIds(topicIds?: Array<string>, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
let localVarQueryParameters = new HttpParams({encoder: this.encoder}); const localVarHttpHeaderAcceptSelected: string | undefined =
if (topicIds) { options?.httpHeaderAccept ??
topicIds.forEach((element) => { this.configuration.selectHeaderAccept(['application/json']);
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters, if (localVarHttpHeaderAcceptSelected !== undefined) {
<any>element, 'topic_ids'); localVarHeaders = localVarHeaders.set(
}) 'Accept',
} localVarHttpHeaderAcceptSelected,
);
let localVarHeaders = this.defaultHeaders;
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
'application/json'
]);
if (localVarHttpHeaderAcceptSelected !== undefined) {
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
}
const localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/topics/v2/topics/id`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<TopicPageV2>('get', `${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
reportProgress: reportProgress
}
);
} }
const localVarHttpContext: HttpContext =
options?.context ?? new HttpContext();
const localVarTransferCache: boolean = options?.transferCache ?? true;
let responseType_: 'text' | 'json' | 'blob' = 'json';
if (localVarHttpHeaderAcceptSelected) {
if (localVarHttpHeaderAcceptSelected.startsWith('text')) {
responseType_ = 'text';
} else if (
this.configuration.isJsonMime(localVarHttpHeaderAcceptSelected)
) {
responseType_ = 'json';
} else {
responseType_ = 'blob';
}
}
let localVarPath = `/api/topics/v2/topics/id`;
const { basePath, withCredentials } = this.configuration;
return this.httpClient.request<TopicPageV2>(
'get',
`${basePath}${localVarPath}`,
{
context: localVarHttpContext,
params: localVarQueryParameters,
responseType: <any>responseType_,
...(withCredentials ? { withCredentials } : {}),
headers: localVarHeaders,
observe: observe,
...(localVarTransferCache !== undefined
? { transferCache: localVarTransferCache }
: {}),
reportProgress: reportProgress,
},
);
}
} }
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+197 -171
View File
@@ -1,193 +1,219 @@
import { HttpHeaders, HttpParams, HttpParameterCodec } from '@angular/common/http'; import {
HttpHeaders,
HttpParams,
HttpParameterCodec,
} from '@angular/common/http';
import { Param } from './param'; import { Param } from './param';
export interface ConfigurationParameters { export interface ConfigurationParameters {
/** /**
* @deprecated Since 5.0. Use credentials instead * @deprecated Since 5.0. Use credentials instead
*/ */
apiKeys?: {[ key: string ]: string}; apiKeys?: { [key: string]: string };
username?: string; username?: string;
password?: string; password?: string;
/** /**
* @deprecated Since 5.0. Use credentials instead * @deprecated Since 5.0. Use credentials instead
*/ */
accessToken?: string | (() => string); accessToken?: string | (() => string);
basePath?: string; basePath?: string;
withCredentials?: boolean; withCredentials?: boolean;
/** /**
* Takes care of encoding query- and form-parameters. * Takes care of encoding query- and form-parameters.
*/ */
encoder?: HttpParameterCodec; encoder?: HttpParameterCodec;
/** /**
* Override the default method for encoding path parameters in various * Override the default method for encoding path parameters in various
* <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values">styles</a>. * <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values">styles</a>.
* <p> * <p>
* See {@link README.md} for more details * See {@link README.md} for more details
* </p> * </p>
*/ */
encodeParam?: (param: Param) => string; encodeParam?: (param: Param) => string;
/** /**
* The keys are the names in the securitySchemes section of the OpenAPI * The keys are the names in the securitySchemes section of the OpenAPI
* document. They should map to the value used for authentication * document. They should map to the value used for authentication
* minus any standard prefixes such as 'Basic' or 'Bearer'. * minus any standard prefixes such as 'Basic' or 'Bearer'.
*/ */
credentials?: {[ key: string ]: string | (() => string | undefined)}; credentials?: { [key: string]: string | (() => string | undefined) };
} }
export class Configuration { export class Configuration {
/** /**
* @deprecated Since 5.0. Use credentials instead * @deprecated Since 5.0. Use credentials instead
*/ */
apiKeys?: {[ key: string ]: string}; apiKeys?: { [key: string]: string };
username?: string; username?: string;
password?: string; password?: string;
/** /**
* @deprecated Since 5.0. Use credentials instead * @deprecated Since 5.0. Use credentials instead
*/ */
accessToken?: string | (() => string); accessToken?: string | (() => string);
basePath?: string; basePath?: string;
withCredentials?: boolean; withCredentials?: boolean;
/** /**
* Takes care of encoding query- and form-parameters. * Takes care of encoding query- and form-parameters.
*/ */
encoder?: HttpParameterCodec; encoder?: HttpParameterCodec;
/** /**
* Encoding of various path parameter * Encoding of various path parameter
* <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values">styles</a>. * <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values">styles</a>.
* <p> * <p>
* See {@link README.md} for more details * See {@link README.md} for more details
* </p> * </p>
*/ */
encodeParam: (param: Param) => string; encodeParam: (param: Param) => string;
/** /**
* The keys are the names in the securitySchemes section of the OpenAPI * The keys are the names in the securitySchemes section of the OpenAPI
* document. They should map to the value used for authentication * document. They should map to the value used for authentication
* minus any standard prefixes such as 'Basic' or 'Bearer'. * minus any standard prefixes such as 'Basic' or 'Bearer'.
*/ */
credentials: {[ key: string ]: string | (() => string | undefined)}; credentials: { [key: string]: string | (() => string | undefined) };
constructor({ accessToken, apiKeys, basePath, credentials, encodeParam, encoder, password, username, withCredentials }: ConfigurationParameters = {}) { constructor({
if (apiKeys) { accessToken,
this.apiKeys = apiKeys; apiKeys,
} basePath,
if (username !== undefined) { credentials,
this.username = username; encodeParam,
} encoder,
if (password !== undefined) { password,
this.password = password; username,
} withCredentials,
if (accessToken !== undefined) { }: ConfigurationParameters = {}) {
this.accessToken = accessToken; if (apiKeys) {
} this.apiKeys = apiKeys;
if (basePath !== undefined) { }
this.basePath = basePath; if (username !== undefined) {
} this.username = username;
if (withCredentials !== undefined) { }
this.withCredentials = withCredentials; if (password !== undefined) {
} this.password = password;
if (encoder) { }
this.encoder = encoder; if (accessToken !== undefined) {
} this.accessToken = accessToken;
this.encodeParam = encodeParam ?? (param => this.defaultEncodeParam(param)); }
this.credentials = credentials ?? {}; if (basePath !== undefined) {
this.basePath = basePath;
}
if (withCredentials !== undefined) {
this.withCredentials = withCredentials;
}
if (encoder) {
this.encoder = encoder;
}
this.encodeParam =
encodeParam ?? ((param) => this.defaultEncodeParam(param));
this.credentials = credentials ?? {};
// init default HTTPBearer credential // init default HTTPBearer credential
if (!this.credentials['HTTPBearer']) { if (!this.credentials['HTTPBearer']) {
this.credentials['HTTPBearer'] = () => { this.credentials['HTTPBearer'] = () => {
return typeof this.accessToken === 'function' return typeof this.accessToken === 'function'
? this.accessToken() ? this.accessToken()
: this.accessToken; : this.accessToken;
}; };
} }
}
/**
* Select the correct content-type to use for a request.
* Uses {@link Configuration#isJsonMime} to determine the correct content-type.
* If no content type is found return the first found type if the contentTypes is not empty
* @param contentTypes - the array of content types that are available for selection
* @returns the selected content-type or <code>undefined</code> if no selection could be made.
*/
public selectHeaderContentType(contentTypes: string[]): string | undefined {
if (contentTypes.length === 0) {
return undefined;
} }
/** const type = contentTypes.find((x: string) => this.isJsonMime(x));
* Select the correct content-type to use for a request. if (type === undefined) {
* Uses {@link Configuration#isJsonMime} to determine the correct content-type. return contentTypes[0];
* If no content type is found return the first found type if the contentTypes is not empty }
* @param contentTypes - the array of content types that are available for selection return type;
* @returns the selected content-type or <code>undefined</code> if no selection could be made. }
*/
public selectHeaderContentType (contentTypes: string[]): string | undefined {
if (contentTypes.length === 0) {
return undefined;
}
const type = contentTypes.find((x: string) => this.isJsonMime(x)); /**
if (type === undefined) { * Select the correct accept content-type to use for a request.
return contentTypes[0]; * Uses {@link Configuration#isJsonMime} to determine the correct accept content-type.
} * If no content type is found return the first found type if the contentTypes is not empty
return type; * @param accepts - the array of content types that are available for selection.
* @returns the selected content-type or <code>undefined</code> if no selection could be made.
*/
public selectHeaderAccept(accepts: string[]): string | undefined {
if (accepts.length === 0) {
return undefined;
} }
/** const type = accepts.find((x: string) => this.isJsonMime(x));
* Select the correct accept content-type to use for a request. if (type === undefined) {
* Uses {@link Configuration#isJsonMime} to determine the correct accept content-type. return accepts[0];
* If no content type is found return the first found type if the contentTypes is not empty
* @param accepts - the array of content types that are available for selection.
* @returns the selected content-type or <code>undefined</code> if no selection could be made.
*/
public selectHeaderAccept(accepts: string[]): string | undefined {
if (accepts.length === 0) {
return undefined;
}
const type = accepts.find((x: string) => this.isJsonMime(x));
if (type === undefined) {
return accepts[0];
}
return type;
} }
return type;
}
/** /**
* Check if the given MIME is a JSON MIME. * Check if the given MIME is a JSON MIME.
* JSON MIME examples: * JSON MIME examples:
* application/json * application/json
* application/json; charset=UTF8 * application/json; charset=UTF8
* APPLICATION/JSON * APPLICATION/JSON
* application/vnd.company+json * application/vnd.company+json
* @param mime - MIME (Multipurpose Internet Mail Extensions) * @param mime - MIME (Multipurpose Internet Mail Extensions)
* @return True if the given MIME is JSON, false otherwise. * @return True if the given MIME is JSON, false otherwise.
*/ */
public isJsonMime(mime: string): boolean { public isJsonMime(mime: string): boolean {
const jsonMime: RegExp = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i'); const jsonMime: RegExp = new RegExp(
return mime !== null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json'); '^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$',
} 'i',
);
return (
mime !== null &&
(jsonMime.test(mime) ||
mime.toLowerCase() === 'application/json-patch+json')
);
}
public lookupCredential(key: string): string | undefined { public lookupCredential(key: string): string | undefined {
const value = this.credentials[key]; const value = this.credentials[key];
return typeof value === 'function' return typeof value === 'function' ? value() : value;
? value() }
: value;
}
public addCredentialToHeaders(credentialKey: string, headerName: string, headers: HttpHeaders, prefix?: string): HttpHeaders { public addCredentialToHeaders(
const value = this.lookupCredential(credentialKey); credentialKey: string,
return value headerName: string,
? headers.set(headerName, (prefix ?? '') + value) headers: HttpHeaders,
: headers; prefix?: string,
} ): HttpHeaders {
const value = this.lookupCredential(credentialKey);
return value ? headers.set(headerName, (prefix ?? '') + value) : headers;
}
public addCredentialToQuery(credentialKey: string, paramName: string, query: HttpParams): HttpParams { public addCredentialToQuery(
const value = this.lookupCredential(credentialKey); credentialKey: string,
return value paramName: string,
? query.set(paramName, value) query: HttpParams,
: query; ): HttpParams {
} const value = this.lookupCredential(credentialKey);
return value ? query.set(paramName, value) : query;
}
private defaultEncodeParam(param: Param): string { private defaultEncodeParam(param: Param): string {
// This implementation exists as fallback for missing configuration // This implementation exists as fallback for missing configuration
// and for backwards compatibility to older typescript-angular generator versions. // and for backwards compatibility to older typescript-angular generator versions.
// It only works for the 'simple' parameter style. // It only works for the 'simple' parameter style.
// Date-handling only works for the 'date-time' format. // Date-handling only works for the 'date-time' format.
// All other styles and Date-formats are probably handled incorrectly. // All other styles and Date-formats are probably handled incorrectly.
// //
// But: if that's all you need (i.e.: the most common use-case): no need for customization! // But: if that's all you need (i.e.: the most common use-case): no need for customization!
const value = param.dataFormat === 'date-time' && param.value instanceof Date const value =
? (param.value as Date).toISOString() param.dataFormat === 'date-time' && param.value instanceof Date
: param.value; ? (param.value as Date).toISOString()
: param.value;
return encodeURIComponent(String(value)); return encodeURIComponent(String(value));
} }
} }
+12 -12
View File
@@ -5,16 +5,16 @@ import { HttpParameterCodec } from '@angular/common/http';
* Workaround for https://github.com/angular/angular/issues/18261 * Workaround for https://github.com/angular/angular/issues/18261
*/ */
export class CustomHttpParameterCodec implements HttpParameterCodec { export class CustomHttpParameterCodec implements HttpParameterCodec {
encodeKey(k: string): string { encodeKey(k: string): string {
return encodeURIComponent(k); return encodeURIComponent(k);
} }
encodeValue(v: string): string { encodeValue(v: string): string {
return encodeURIComponent(v); return encodeURIComponent(v);
} }
decodeKey(k: string): string { decodeKey(k: string): string {
return decodeURIComponent(k); return decodeURIComponent(k);
} }
decodeValue(v: string): string { decodeValue(v: string): string {
return decodeURIComponent(v); return decodeURIComponent(v);
} }
} }
+4 -6
View File
@@ -9,11 +9,9 @@
*/ */
import { AccessToken } from './accessToken'; import { AccessToken } from './accessToken';
export interface AccessResponse { export interface AccessResponse {
/** /**
* The access token issued upon successful authentication. * The access token issued upon successful authentication.
*/ */
access_token: AccessToken; access_token: AccessToken;
} }
+42 -46
View File
@@ -10,51 +10,47 @@
import { TokenType } from './tokenType'; import { TokenType } from './tokenType';
import { UserRole } from './userRole'; import { UserRole } from './userRole';
export interface AccessToken { export interface AccessToken {
/** /**
* The unique identifier of the real account associated with this token. * The unique identifier of the real account associated with this token.
*/ */
real_account_id: string; real_account_id: string;
/** /**
* The timestamp indicating when the token will expire. * The timestamp indicating when the token will expire.
*/ */
expires_at: string; expires_at: string;
/** /**
* The epoch value for the token. Used for versioning of tokens. * The epoch value for the token. Used for versioning of tokens.
*/ */
epoch?: number; epoch?: number;
/** /**
* The type of the token, which is always ACCESS_TOKEN for this class. * The type of the token, which is always ACCESS_TOKEN for this class.
*/ */
token_type?: TokenType; token_type?: TokenType;
/** /**
* A unique fingerprint of the user, used for additional security checks. * A unique fingerprint of the user, used for additional security checks.
*/ */
user_fingerprint_hash: string; user_fingerprint_hash: string;
/** /**
* The unique identifier of the effective account associated with this access token. This may differ from the real account ID due to account impersonation. * The unique identifier of the effective account associated with this access token. This may differ from the real account ID due to account impersonation.
*/ */
effective_account_id: string; effective_account_id: string;
/** /**
* The specific role this access token grants within its organization. * The specific role this access token grants within its organization.
*/ */
effective_role?: UserRole; effective_role?: UserRole;
/** /**
* The roles this access token grants within its organization. * The roles this access token grants within its organization.
*/ */
effective_roles?: Array<UserRole>; effective_roles?: Array<UserRole>;
/** /**
* The unique identifier of the organization associated with this access token. * The unique identifier of the organization associated with this access token.
*/ */
effective_organization_id: string; effective_organization_id: string;
effective_institution_id?: string | null; effective_institution_id?: string | null;
/** /**
* The raw string representation of the access token. This is the actual token that can be used for authentication and authorization purposes. * The raw string representation of the access token. This is the actual token that can be used for authentication and authorization purposes.
*/ */
raw_token: string; raw_token: string;
} }
export namespace AccessToken { export namespace AccessToken {}
}
+4 -6
View File
@@ -9,11 +9,9 @@
*/ */
import { AccountProfile } from './accountProfile'; import { AccountProfile } from './accountProfile';
export interface AccountPage { export interface AccountPage {
items: Array<AccountProfile>; items: Array<AccountProfile>;
total: number; total: number;
page: number; page: number;
page_size: number; page_size: number;
} }
+11 -13
View File
@@ -9,18 +9,16 @@
*/ */
import { UserRole } from './userRole'; import { UserRole } from './userRole';
export interface AccountProfile { export interface AccountProfile {
id: string; id: string;
email: string; email: string;
name: string; name: string;
roles: Array<UserRole>; roles: Array<UserRole>;
organization_id: string; organization_id: string;
organization_name: string; organization_name: string;
deleted: boolean; deleted: boolean;
activated: boolean; activated: boolean;
is_current?: boolean; is_current?: boolean;
is_real_account?: boolean; is_real_account?: boolean;
is_impersonating?: boolean; is_impersonating?: boolean;
} }
@@ -9,11 +9,9 @@
*/ */
import { PatentEntry } from './patentEntry'; import { PatentEntry } from './patentEntry';
export interface AllPatentsResponse { export interface AllPatentsResponse {
total: number; total: number;
page: number; page: number;
size: number; size: number;
patents: Array<PatentEntry>; patents: Array<PatentEntry>;
} }
+17 -19
View File
@@ -15,27 +15,25 @@ import { AuthorIds } from './authorIds';
import { AuthorSummaryStats } from './authorSummaryStats'; import { AuthorSummaryStats } from './authorSummaryStats';
import { WorkTopic } from './workTopic'; import { WorkTopic } from './workTopic';
/** /**
* A person who creates scholarly works * A person who creates scholarly works
*/ */
export interface Author { export interface Author {
id?: string | null; id?: string | null;
orcid?: string | null; orcid?: string | null;
display_name?: string | null; display_name?: string | null;
display_name_alternatives?: Array<string> | null; display_name_alternatives?: Array<string> | null;
longest_name?: string | null; longest_name?: string | null;
parsed_longest_name?: AuthorParsedLongestName | null; parsed_longest_name?: AuthorParsedLongestName | null;
works_count?: number | null; works_count?: number | null;
cited_by_count?: number | null; cited_by_count?: number | null;
summary_stats?: AuthorSummaryStats | null; summary_stats?: AuthorSummaryStats | null;
affiliations?: Array<AuthorAffiliationsInner> | null; affiliations?: Array<AuthorAffiliationsInner> | null;
last_known_institutions?: Array<DehydratedInstitution> | null; last_known_institutions?: Array<DehydratedInstitution> | null;
topics?: Array<WorkTopic> | null; topics?: Array<WorkTopic> | null;
counts_by_year?: Array<AuthorCountsByYearInner> | null; counts_by_year?: Array<AuthorCountsByYearInner> | null;
ids?: AuthorIds | null; ids?: AuthorIds | null;
works_api_url?: string | null; works_api_url?: string | null;
created_date?: string | null; created_date?: string | null;
updated_date?: string | null; updated_date?: string | null;
} }
@@ -9,12 +9,10 @@
*/ */
import { DehydratedInstitution } from './dehydratedInstitution'; import { DehydratedInstitution } from './dehydratedInstitution';
/** /**
* AuthorAffiliationsInner * AuthorAffiliationsInner
*/ */
export interface AuthorAffiliationsInner { export interface AuthorAffiliationsInner {
institution?: DehydratedInstitution | null; institution?: DehydratedInstitution | null;
years?: Array<number> | null; years?: Array<number> | null;
} }
@@ -8,13 +8,11 @@
* Do not edit the class manually. * Do not edit the class manually.
*/ */
/** /**
* AuthorCountsByYearInner * AuthorCountsByYearInner
*/ */
export interface AuthorCountsByYearInner { export interface AuthorCountsByYearInner {
year?: number | null; year?: number | null;
works_count?: number | null; works_count?: number | null;
cited_by_count?: number | null; cited_by_count?: number | null;
} }
+3 -5
View File
@@ -8,13 +8,11 @@
* Do not edit the class manually. * Do not edit the class manually.
*/ */
/** /**
* External identifiers: * External identifiers:
*/ */
export interface AuthorIds { export interface AuthorIds {
openalex?: string | null; openalex?: string | null;
orcid?: string | null; orcid?: string | null;
scopus?: string | null; scopus?: string | null;
} }
@@ -9,18 +9,14 @@
*/ */
import { CompanyStatusFilter } from './companyStatusFilter'; import { CompanyStatusFilter } from './companyStatusFilter';
export interface AuthorMetricsRequest { export interface AuthorMetricsRequest {
/** /**
* OpenAlex IDs of the authors. * OpenAlex IDs of the authors.
*/ */
author_ids: Array<string>; author_ids: Array<string>;
/** /**
* Which companies to count for the company-foundations metric: \'all\', only \'active\' (non-deleted), or only \'deleted\'. * Which companies to count for the company-foundations metric: \'all\', only \'active\' (non-deleted), or only \'deleted\'.
*/ */
company_status?: CompanyStatusFilter; company_status?: CompanyStatusFilter;
} }
export namespace AuthorMetricsRequest { export namespace AuthorMetricsRequest {}
}
+13 -17
View File
@@ -9,22 +9,18 @@
*/ */
import { CollaborationNetworkNodeType } from './collaborationNetworkNodeType'; import { CollaborationNetworkNodeType } from './collaborationNetworkNodeType';
export interface AuthorNetworkNode { export interface AuthorNetworkNode {
/** /**
* The raw ID of the node. For an author node, this is the raw person ID. For an institution node, this is the raw institution ID. For a work node, this is the raw work ID. * The raw ID of the node. For an author node, this is the raw person ID. For an institution node, this is the raw institution ID. For a work node, this is the raw work ID.
*/ */
raw_id: string; raw_id: string;
/** /**
* The display name of the node. * The display name of the node.
*/ */
display_name: string; display_name: string;
/** /**
* The category of the node, either \'author\', \'institution\', or \'work\'. * The category of the node, either \'author\', \'institution\', or \'work\'.
*/ */
category: CollaborationNetworkNodeType; category: CollaborationNetworkNodeType;
} }
export namespace AuthorNetworkNode { export namespace AuthorNetworkNode {}
}
+16 -18
View File
@@ -9,26 +9,24 @@
*/ */
import { Author } from './author'; import { Author } from './author';
/** /**
* A paginated response containing a list of authors. * A paginated response containing a list of authors.
*/ */
export interface AuthorPage { export interface AuthorPage {
/** /**
* The elements of the page. * The elements of the page.
*/ */
elements?: Array<Author>; elements?: Array<Author>;
/** /**
* The page number. (0-based) * The page number. (0-based)
*/ */
page?: number; page?: number;
/** /**
* The page size in elements. * The page size in elements.
*/ */
size?: number; size?: number;
/** /**
* The total number of elements. * The total number of elements.
*/ */
total?: number; total?: number;
} }
@@ -8,15 +8,13 @@
* Do not edit the class manually. * Do not edit the class manually.
*/ */
/** /**
* The longest name parsed into its component parts. * The longest name parsed into its component parts.
*/ */
export interface AuthorParsedLongestName { export interface AuthorParsedLongestName {
first?: string | null; first?: string | null;
middle?: string | null; middle?: string | null;
last?: string | null; last?: string | null;
suffix?: string | null; suffix?: string | null;
nickname?: string | null; nickname?: string | null;
} }
@@ -8,11 +8,9 @@
* Do not edit the class manually. * Do not edit the class manually.
*/ */
export interface AuthorPositionCount { export interface AuthorPositionCount {
first?: number; first?: number;
middle?: number; middle?: number;
last?: number; last?: number;
unknown?: number; unknown?: number;
} }
+20 -22
View File
@@ -8,30 +8,28 @@
* Do not edit the class manually. * Do not edit the class manually.
*/ */
/** /**
* Section 2: author-level stats independent of any keyword/topic/time filter. * Section 2: author-level stats independent of any keyword/topic/time filter.
*/ */
export interface AuthorStaticStats { export interface AuthorStaticStats {
/** /**
* The OpenAlex ID of the author. * The OpenAlex ID of the author.
*/ */
author_id: string; author_id: string;
/** /**
* The name of the author. * The name of the author.
*/ */
display_name: string; display_name: string;
/** /**
* Number of Handelsregister company connections matched by the author\'s name. * Number of Handelsregister company connections matched by the author\'s name.
*/ */
companies_count: number; companies_count: number;
/** /**
* Number of news articles that mention the author by exact name. * Number of news articles that mention the author by exact name.
*/ */
news_count: number; news_count: number;
/** /**
* Number of patents matched to the author (from the org_patents index). * Number of patents matched to the author (from the org_patents index).
*/ */
patents_count: number; patents_count: number;
} }
@@ -9,13 +9,11 @@
*/ */
import { Model2YrMeanCitedness } from './model2YrMeanCitedness'; import { Model2YrMeanCitedness } from './model2YrMeanCitedness';
/** /**
* Citation metrics: * Citation metrics:
*/ */
export interface AuthorSummaryStats { export interface AuthorSummaryStats {
'2yr_mean_citedness'?: Model2YrMeanCitedness | null; '2yr_mean_citedness'?: Model2YrMeanCitedness | null;
h_index?: number | null; h_index?: number | null;
i10_index?: number | null; i10_index?: number | null;
} }
+36 -38
View File
@@ -9,43 +9,41 @@
*/ */
import { SubfieldShare } from './subfieldShare'; import { SubfieldShare } from './subfieldShare';
export interface AuthorTopicProfile { export interface AuthorTopicProfile {
/** /**
* The OpenAlex ID of the author. * The OpenAlex ID of the author.
*/ */
author_id: string; author_id: string;
/** /**
* The name of the author. * The name of the author.
*/ */
display_name: string; display_name: string;
/** /**
* All works of the author in the timespan, regardless of the topic filter. * All works of the author in the timespan, regardless of the topic filter.
*/ */
works_total: number; works_total: number;
/** /**
* Works matching the topic filter (same subset as Section 1). * Works matching the topic filter (same subset as Section 1).
*/ */
matched_works: number; matched_works: number;
/** /**
* Matched works where one of the searched topics is the work\'s primary topic (only meaningful for filter_type \'topic\'). * Matched works where one of the searched topics is the work\'s primary topic (only meaningful for filter_type \'topic\').
*/ */
primary_topic_matches: number; primary_topic_matches: number;
/** /**
* Number of distinct primary topics across all works. * Number of distinct primary topics across all works.
*/ */
distinct_topics: number; distinct_topics: number;
/** /**
* Number of distinct primary-topic subfields across all works. * Number of distinct primary-topic subfields across all works.
*/ */
distinct_subfields: number; distinct_subfields: number;
/** /**
* Number of distinct primary-topic fields across all works. * Number of distinct primary-topic fields across all works.
*/ */
distinct_fields: number; distinct_fields: number;
/** /**
* Top subfields over all works, by primary topic, largest first. * Top subfields over all works, by primary topic, largest first.
*/ */
subfields?: Array<SubfieldShare>; subfields?: Array<SubfieldShare>;
} }
+78 -80
View File
@@ -8,88 +8,86 @@
* Do not edit the class manually. * Do not edit the class manually.
*/ */
/** /**
* Section 1: combined stats over an author\'s works that match the topic filter. * Section 1: combined stats over an author\'s works that match the topic filter.
*/ */
export interface AuthorTopicStats { export interface AuthorTopicStats {
/** /**
* The OpenAlex ID of the author. * The OpenAlex ID of the author.
*/ */
author_id: string; author_id: string;
/** /**
* The name of the author. * The name of the author.
*/ */
display_name: string; display_name: string;
/** /**
* Number of the author\'s works matching the topic filter. * Number of the author\'s works matching the topic filter.
*/ */
works_total: number; works_total: number;
/** /**
* Number of the author\'s topic works where they are the corresponding author. * Number of the author\'s topic works where they are the corresponding author.
*/ */
corresponding_count: number; corresponding_count: number;
/** /**
* Average field-normalized citation percentile (0-1) over the author\'s topic works. * Average field-normalized citation percentile (0-1) over the author\'s topic works.
*/ */
avg_percentile: number; avg_percentile: number;
/** /**
* Number of the author\'s topic works in the top 1% most-cited. * Number of the author\'s topic works in the top 1% most-cited.
*/ */
top1_count: number; top1_count: number;
/** /**
* Number of the author\'s topic works in the top 10% most-cited. * Number of the author\'s topic works in the top 10% most-cited.
*/ */
top10_count: number; top10_count: number;
/** /**
* Number of the author\'s topic works with a field-weighted citation impact (FWCI) above 1 (cited more than the field/year/type average). * Number of the author\'s topic works with a field-weighted citation impact (FWCI) above 1 (cited more than the field/year/type average).
*/ */
fwci_above_one_count?: number; fwci_above_one_count?: number;
/** /**
* Total citations across the author\'s topic works. * Total citations across the author\'s topic works.
*/ */
citations_total?: number; citations_total?: number;
/** /**
* Average citations per topic work. * Average citations per topic work.
*/ */
avg_citations?: number; avg_citations?: number;
/** /**
* Citations of the author\'s most-cited topic work. * Citations of the author\'s most-cited topic work.
*/ */
max_citations?: number; max_citations?: number;
/** /**
* h-index over the author\'s topic works (capped at 100). * h-index over the author\'s topic works (capped at 100).
*/ */
h_index?: number; h_index?: number;
/** /**
* Average field-weighted citation impact (FWCI) over the author\'s topic works; works without an FWCI value are excluded. * Average field-weighted citation impact (FWCI) over the author\'s topic works; works without an FWCI value are excluded.
*/ */
avg_fwci?: number; avg_fwci?: number;
/** /**
* Number of the author\'s topic works with at least one co-author institution of type \'company\'. * Number of the author\'s topic works with at least one co-author institution of type \'company\'.
*/ */
industry_works_count?: number; industry_works_count?: number;
first_year?: number | null; first_year?: number | null;
last_year?: number | null; last_year?: number | null;
/** /**
* Number of the author\'s topic works where the matched keyword\'s relevance score is above 0.8. * Number of the author\'s topic works where the matched keyword\'s relevance score is above 0.8.
*/ */
relevance_above_80_count?: number; relevance_above_80_count?: number;
/** /**
* Average matched-keyword relevance score (0-1) over the author\'s topic works. * Average matched-keyword relevance score (0-1) over the author\'s topic works.
*/ */
avg_relevance?: number; avg_relevance?: number;
/** /**
* Number of the author\'s topic works where they are the first author. * Number of the author\'s topic works where they are the first author.
*/ */
first_author_count?: number; first_author_count?: number;
/** /**
* Number of the author\'s topic works where they are a middle author. * Number of the author\'s topic works where they are a middle author.
*/ */
middle_author_count?: number; middle_author_count?: number;
/** /**
* Number of the author\'s topic works where they are the last author. * Number of the author\'s topic works where they are the last author.
*/ */
last_author_count?: number; last_author_count?: number;
} }
@@ -8,19 +8,17 @@
* Do not edit the class manually. * Do not edit the class manually.
*/ */
export interface AuthorsFilterProperties { export interface AuthorsFilterProperties {
/** /**
* The list of raw institution IDs to include in the collaboration network. If empty, all institutions will be included. * The list of raw institution IDs to include in the collaboration network. If empty, all institutions will be included.
*/ */
allowed_institutions?: Array<string>; allowed_institutions?: Array<string>;
/** /**
* The minimum number of collaborations required for an author to be included in the collaboration network. * The minimum number of collaborations required for an author to be included in the collaboration network.
*/ */
min_collaborations?: number; min_collaborations?: number;
/** /**
* The maximum number of collaborations allowed for an author to be included in the collaboration network. * The maximum number of collaborations allowed for an author to be included in the collaboration network.
*/ */
max_collaborations?: number; max_collaborations?: number;
} }
@@ -11,13 +11,11 @@ import { Meta } from './meta';
import { Author } from './author'; import { Author } from './author';
import { GroupByResult } from './groupByResult'; import { GroupByResult } from './groupByResult';
/** /**
* AuthorsListResponse * AuthorsListResponse
*/ */
export interface AuthorsListResponse { export interface AuthorsListResponse {
meta?: Meta | null; meta?: Meta | null;
results?: Array<Author> | null; results?: Array<Author> | null;
group_by?: Array<GroupByResult> | null; group_by?: Array<GroupByResult> | null;
} }
+7 -9
View File
@@ -10,17 +10,15 @@
import { DehydratedInstitution } from './dehydratedInstitution'; import { DehydratedInstitution } from './dehydratedInstitution';
import { DehydratedAuthor } from './dehydratedAuthor'; import { DehydratedAuthor } from './dehydratedAuthor';
/** /**
* Author and their affiliation for a work * Author and their affiliation for a work
*/ */
export interface Authorship { export interface Authorship {
author_position?: string | null; author_position?: string | null;
author?: DehydratedAuthor | null; author?: DehydratedAuthor | null;
institutions?: Array<DehydratedInstitution> | null; institutions?: Array<DehydratedInstitution> | null;
countries?: Array<string> | null; countries?: Array<string> | null;
is_corresponding?: boolean | null; is_corresponding?: boolean | null;
raw_author_name?: string | null; raw_author_name?: string | null;
raw_affiliation_strings?: Array<string> | null; raw_affiliation_strings?: Array<string> | null;
} }
@@ -8,19 +8,16 @@
* Do not edit the class manually. * Do not edit the class manually.
*/ */
export interface AutocompleteLocationItem { export interface AutocompleteLocationItem {
id: string; id: string;
display_name: string; display_name: string;
code: string; code: string;
type: AutocompleteLocationItem.TypeEnum; type: AutocompleteLocationItem.TypeEnum;
} }
export namespace AutocompleteLocationItem { export namespace AutocompleteLocationItem {
export const TypeEnum = { export const TypeEnum = {
Country: 'country', Country: 'country',
Continent: 'continent' Continent: 'continent',
} as const; } as const;
export type TypeEnum = typeof TypeEnum[keyof typeof TypeEnum]; export type TypeEnum = (typeof TypeEnum)[keyof typeof TypeEnum];
} }
@@ -10,12 +10,10 @@
import { AutocompleteResponseMeta } from './autocompleteResponseMeta'; import { AutocompleteResponseMeta } from './autocompleteResponseMeta';
import { AutocompleteResponseResultsInner } from './autocompleteResponseResultsInner'; import { AutocompleteResponseResultsInner } from './autocompleteResponseResultsInner';
/** /**
* AutocompleteResponse * AutocompleteResponse
*/ */
export interface AutocompleteResponse { export interface AutocompleteResponse {
meta?: AutocompleteResponseMeta | null; meta?: AutocompleteResponseMeta | null;
results?: Array<AutocompleteResponseResultsInner> | null; results?: Array<AutocompleteResponseResultsInner> | null;
} }
@@ -8,12 +8,10 @@
* Do not edit the class manually. * Do not edit the class manually.
*/ */
/** /**
* AutocompleteResponseMeta * AutocompleteResponseMeta
*/ */
export interface AutocompleteResponseMeta { export interface AutocompleteResponseMeta {
count?: number | null; count?: number | null;
db_response_time_ms?: number | null; db_response_time_ms?: number | null;
} }
@@ -8,17 +8,15 @@
* Do not edit the class manually. * Do not edit the class manually.
*/ */
/** /**
* AutocompleteResponseResultsInner * AutocompleteResponseResultsInner
*/ */
export interface AutocompleteResponseResultsInner { export interface AutocompleteResponseResultsInner {
id?: string | null; id?: string | null;
display_name?: string | null; display_name?: string | null;
hint?: string | null; hint?: string | null;
cited_by_count?: number | null; cited_by_count?: number | null;
works_count?: number | null; works_count?: number | null;
entity_type?: string | null; entity_type?: string | null;
external_id?: string | null; external_id?: string | null;
} }

Some files were not shown because too many files have changed in this diff Show More