Compare commits
108
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ecf7a6f905 | ||
|
|
7b912196e9 | ||
|
|
6e4742206f | ||
|
|
a28ecc9d02 | ||
|
|
53397f844e | ||
|
|
818398ccda | ||
|
|
a6c7068ca6 | ||
|
|
4785bb4d40 | ||
|
|
1a9f9496fd | ||
|
|
78f35daa58 | ||
|
|
b2e70c2bb3 | ||
|
|
3d8ceeb5b6 | ||
|
|
0b8540d70b | ||
|
|
e9ccfe6796 | ||
|
|
e20f2732b3 | ||
|
|
4da4ea1bff | ||
|
|
93ba39f9b0 | ||
|
|
0642a3704d | ||
|
|
57e1bafa8b | ||
|
|
3d5eb524aa | ||
|
|
c15afed0aa | ||
|
|
b133ce80c9 | ||
|
|
ae8332dc3d | ||
|
|
026a35dd90 | ||
|
|
5fdc1cdce3 | ||
|
|
02bb8b8fb8 | ||
|
|
6af1747477 | ||
|
|
401b82c226 | ||
|
|
9d128e18b6 | ||
|
|
a6a78bb556 | ||
|
|
bc59c3f563 | ||
|
|
8b7ac08192 | ||
|
|
4fe78c2b88 | ||
|
|
2e8dd00aa6 | ||
|
|
127eed5c49 | ||
|
|
7a84fc2b12 | ||
|
|
96e0925054 | ||
|
|
730ee7f89a | ||
|
|
e62d1ca458 | ||
|
|
6bca5643ee | ||
|
|
db20b23ff3 | ||
|
|
66f34668a9 | ||
|
|
ceadc26741 | ||
|
|
3a74dc9b7b | ||
|
|
4a47d752cb | ||
|
|
1bca6648bd | ||
|
|
af00bc4635 | ||
|
|
def210b4b9 | ||
|
|
89bdab0a26 | ||
|
|
448922d907 | ||
|
|
3ef8c28191 | ||
|
|
46aee46ea3 | ||
|
|
e57875d2a5 | ||
|
|
28726cf4c7 | ||
|
|
b0e4ad639e | ||
|
|
1810918e43 | ||
|
|
a736539851 | ||
|
|
591233e255 | ||
|
|
c2a2a31fb9 | ||
|
|
d4a4bfa2c7 | ||
|
|
3a127450e3 | ||
|
|
c2f9a6381a | ||
|
|
7adf12912f | ||
|
|
0b2b05ae85 | ||
|
|
127c32dce7 | ||
|
|
652ff8db15 | ||
|
|
79c1076272 | ||
|
|
d29028a5bd | ||
|
|
8cba5387c7 | ||
|
|
bdb546db12 | ||
|
|
59ed0ad1a4 | ||
|
|
3d57dda846 | ||
|
|
6cdf5f4704 | ||
|
|
9f4bb77208 | ||
|
|
aa05beb594 | ||
|
|
be556f09ad | ||
|
|
2fc9722914 | ||
|
|
9e39650899 | ||
|
|
1860e7c371 | ||
|
|
bf5d626209 | ||
|
|
424649ecdc | ||
|
|
11ac6525c1 | ||
|
|
8a684c8b57 | ||
|
|
90ec5c2c8d | ||
|
|
cbbcaa2325 | ||
|
|
e6eabf08c9 | ||
|
|
b616d061bb | ||
|
|
3a78519655 | ||
|
|
c6de85d4a0 | ||
|
|
71fe4a54e7 | ||
|
|
e7afd7e68a | ||
|
|
f25c5cd222 | ||
|
|
0b5c6bed37 | ||
|
|
2d485263d1 | ||
|
|
3d78ec900e | ||
|
|
fc134dad8e | ||
|
|
59a1f765d0 | ||
|
|
0dd2023224 | ||
|
|
d4880b417b | ||
|
|
a7ced052dd | ||
|
|
9ac618ebec | ||
|
|
de6339586f | ||
|
|
97c9e2eec3 | ||
|
|
167913aa85 | ||
|
|
18c9785325 | ||
|
|
f4e0888ce2 | ||
|
|
d3266ee50e | ||
|
|
410bcdec4b |
@@ -0,0 +1 @@
|
||||
Perhaps not the final version. I did not find the files inside my local git branch. I most likely did not save them, however i made backups sometimes, so i hope these versions are the final ones.
|
||||
@@ -0,0 +1,428 @@
|
||||
#!/usr/bin/env python3
|
||||
import os
|
||||
import sys
|
||||
import json
|
||||
import time
|
||||
import asyncio
|
||||
from pathlib import Path
|
||||
import httpx
|
||||
import numpy as np
|
||||
|
||||
# Load service environment config
|
||||
current_dir = Path(__file__).parent.resolve()
|
||||
project_root = current_dir.parent.parent.resolve()
|
||||
env_path = project_root / "service" / "src" / "main" / "inse" / ".env"
|
||||
|
||||
from dotenv import load_dotenv
|
||||
load_dotenv(dotenv_path=env_path)
|
||||
|
||||
sys.path.append(str(project_root / "service" / "src" / "main"))
|
||||
|
||||
from inse.config import settings
|
||||
from inse.util import get_model
|
||||
|
||||
ELASTIC_URL = settings.elasticsearch_url
|
||||
if ELASTIC_URL and not ELASTIC_URL.endswith("/"):
|
||||
ELASTIC_URL += "/"
|
||||
API_KEY = settings.elasticsearch_api_key
|
||||
|
||||
headers = {
|
||||
"Authorization": f"ApiKey {API_KEY}",
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
|
||||
FIELDS = [
|
||||
"Social Sciences", "Medicine", "Engineering", "Computer Science",
|
||||
"Arts and Humanities", "Biochemistry, Genetics and Molecular Biology",
|
||||
"Agricultural and Biological Sciences", "Environmental Science",
|
||||
"Business, Management and Accounting", "Psychology", "Materials Science",
|
||||
"Economics, Econometrics and Finance", "Health Professions",
|
||||
"Physics and Astronomy", "Chemistry", "Mathematics", "Neuroscience",
|
||||
"Decision Sciences", "Earth and Planetary Sciences", "Immunology and Microbiology",
|
||||
"Energy", "Pharmacology, Toxicology and Pharmaceutics", "Nursing",
|
||||
"Chemical Engineering", "Dentistry", "Veterinary"
|
||||
]
|
||||
|
||||
QUERIES_FILE = current_dir / "evaluation_queries.json"
|
||||
|
||||
def load_queries():
|
||||
if QUERIES_FILE.exists():
|
||||
print(f"Loading cached queries from {QUERIES_FILE}...")
|
||||
with open(QUERIES_FILE, "r", encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
else:
|
||||
raise FileNotFoundError(f"Evaluation queries file not found at {QUERIES_FILE}")
|
||||
|
||||
def make_es_payload(query_vector, query_str, config_type, limit=10):
|
||||
if config_type == "display_name":
|
||||
clause = {
|
||||
"knn": {
|
||||
"field": "display_name_vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
}
|
||||
query_body = {"query": clause}
|
||||
elif config_type == "description":
|
||||
clause = {
|
||||
"knn": {
|
||||
"field": "description_vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
}
|
||||
query_body = {"query": clause}
|
||||
elif config_type == "keywords":
|
||||
clause = {
|
||||
"nested": {
|
||||
"path": "keyword_vectors",
|
||||
"query": {
|
||||
"knn": {
|
||||
"field": "keyword_vectors.vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
},
|
||||
"score_mode": "max"
|
||||
}
|
||||
}
|
||||
query_body = {"query": clause}
|
||||
elif config_type == "display_name_and_keywords":
|
||||
query_body = {
|
||||
"query": {
|
||||
"bool": {
|
||||
"should": [
|
||||
{
|
||||
"knn": {
|
||||
"field": "display_name_vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
},
|
||||
{
|
||||
"nested": {
|
||||
"path": "keyword_vectors",
|
||||
"query": {
|
||||
"knn": {
|
||||
"field": "keyword_vectors.vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
},
|
||||
"score_mode": "max"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
elif config_type == "display_name_and_description":
|
||||
query_body = {
|
||||
"query": {
|
||||
"bool": {
|
||||
"should": [
|
||||
{
|
||||
"knn": {
|
||||
"field": "display_name_vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
},
|
||||
{
|
||||
"knn": {
|
||||
"field": "description_vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
elif config_type == "combined":
|
||||
query_body = {
|
||||
"query": {
|
||||
"bool": {
|
||||
"should": [
|
||||
{
|
||||
"knn": {
|
||||
"field": "display_name_vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
},
|
||||
{
|
||||
"knn": {
|
||||
"field": "description_vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
},
|
||||
{
|
||||
"nested": {
|
||||
"path": "keyword_vectors",
|
||||
"query": {
|
||||
"knn": {
|
||||
"field": "keyword_vectors.vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
},
|
||||
"score_mode": "max"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
elif config_type == "lexical_only":
|
||||
query_body = {
|
||||
"query": {
|
||||
"multi_match": {
|
||||
"query": query_str,
|
||||
"fields": ["display_name^3", "keywords^2", "description^1"]
|
||||
}
|
||||
}
|
||||
}
|
||||
elif config_type == "hybrid":
|
||||
query_body = {
|
||||
"query": {
|
||||
"bool": {
|
||||
"should": [
|
||||
{
|
||||
"multi_match": {
|
||||
"query": query_str,
|
||||
"fields": ["display_name^3", "keywords^2", "description^1"]
|
||||
}
|
||||
},
|
||||
{
|
||||
"knn": {
|
||||
"field": "display_name_vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
},
|
||||
{
|
||||
"knn": {
|
||||
"field": "description_vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
},
|
||||
{
|
||||
"nested": {
|
||||
"path": "keyword_vectors",
|
||||
"query": {
|
||||
"knn": {
|
||||
"field": "keyword_vectors.vector",
|
||||
"query_vector": query_vector,
|
||||
"k": limit,
|
||||
"num_candidates": 100,
|
||||
"similarity": 0.62
|
||||
}
|
||||
},
|
||||
"score_mode": "max"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
else:
|
||||
raise ValueError(f"Unknown config_type: {config_type}")
|
||||
|
||||
query_body["_source"] = {
|
||||
"excludes": ["display_name_vector", "description_vector", "keyword_vectors", "description"]
|
||||
}
|
||||
query_body["size"] = limit
|
||||
return query_body
|
||||
|
||||
async def evaluate():
|
||||
queries_by_field = load_queries()
|
||||
|
||||
# 1. Warm up model and connection
|
||||
print("\nWarming up model and Elasticsearch connection...")
|
||||
model = get_model()
|
||||
model.encode("warmup search term")
|
||||
|
||||
# Run a dummy check on ES
|
||||
dummy_vector = [0.1] * 768
|
||||
dummy_payload = make_es_payload(dummy_vector, "warmup search term", "display_name")
|
||||
try:
|
||||
with httpx.Client(timeout=10.0) as client:
|
||||
client.post(f"{ELASTIC_URL}topicvectors/_search", json=dummy_payload, headers=headers)
|
||||
print("Warmup complete.")
|
||||
except Exception as exc:
|
||||
print(f"Warmup query failed: {exc}")
|
||||
|
||||
results = []
|
||||
print("\nRunning comprehensive latency evaluation on 520 queries...")
|
||||
query_count = 0
|
||||
|
||||
config_list = [
|
||||
"display_name", "description", "keywords",
|
||||
"display_name_and_keywords", "display_name_and_description",
|
||||
"combined", "lexical_only", "hybrid"
|
||||
]
|
||||
|
||||
with httpx.Client(timeout=30.0) as client:
|
||||
for field, queries in queries_by_field.items():
|
||||
for q in queries:
|
||||
query_count += 1
|
||||
if query_count % 50 == 0:
|
||||
print(f"Processed {query_count} / 520 queries...")
|
||||
|
||||
# Measure encoding latency
|
||||
t0 = time.perf_counter()
|
||||
query_vector = model.encode(q).tolist()
|
||||
t1 = time.perf_counter()
|
||||
encode_time = (t1 - t0) * 1000.0 # ms
|
||||
|
||||
latencies = {}
|
||||
|
||||
# Benchmark each configuration
|
||||
for config in config_list:
|
||||
payload = make_es_payload(query_vector, q, config)
|
||||
t0 = time.perf_counter()
|
||||
try:
|
||||
resp = client.post(f"{ELASTIC_URL}topicvectors/_search", json=payload, headers=headers)
|
||||
resp.raise_for_status()
|
||||
except Exception as exc:
|
||||
# Log error but don't crash
|
||||
pass
|
||||
t1 = time.perf_counter()
|
||||
latencies[config] = (t1 - t0) * 1000.0 # ms
|
||||
|
||||
results.append({
|
||||
"query": q,
|
||||
"field": field,
|
||||
"encode_latency_ms": encode_time,
|
||||
"display_name_latency_ms": latencies.get("display_name", 0.0),
|
||||
"description_latency_ms": latencies.get("description", 0.0),
|
||||
"keywords_latency_ms": latencies.get("keywords", 0.0),
|
||||
"display_name_and_keywords_latency_ms": latencies.get("display_name_and_keywords", 0.0),
|
||||
"display_name_and_description_latency_ms": latencies.get("display_name_and_description", 0.0),
|
||||
"combined_latency_ms": latencies.get("combined", 0.0),
|
||||
"lexical_only_latency_ms": latencies.get("lexical_only", 0.0),
|
||||
"hybrid_latency_ms": latencies.get("hybrid", 0.0)
|
||||
})
|
||||
|
||||
# Calculate global stats
|
||||
encode_l = [r["encode_latency_ms"] for r in results]
|
||||
display_name_l = [r["display_name_latency_ms"] for r in results]
|
||||
description_l = [r["description_latency_ms"] for r in results]
|
||||
keywords_l = [r["keywords_latency_ms"] for r in results]
|
||||
display_name_and_keywords_l = [r["display_name_and_keywords_latency_ms"] for r in results]
|
||||
display_name_and_description_l = [r["display_name_and_description_latency_ms"] for r in results]
|
||||
combined_l = [r["combined_latency_ms"] for r in results]
|
||||
lexical_only_l = [r["lexical_only_latency_ms"] for r in results]
|
||||
hybrid_l = [r["hybrid_latency_ms"] for r in results]
|
||||
|
||||
summary = {
|
||||
"total_queries": len(results),
|
||||
"encode": {
|
||||
"mean": np.mean(encode_l), "median": np.median(encode_l),
|
||||
"p90": np.percentile(encode_l, 90), "p95": np.percentile(encode_l, 95)
|
||||
},
|
||||
"display_name": {
|
||||
"mean": np.mean(display_name_l), "median": np.median(display_name_l),
|
||||
"p90": np.percentile(display_name_l, 90), "p95": np.percentile(display_name_l, 95)
|
||||
},
|
||||
"description": {
|
||||
"mean": np.mean(description_l), "median": np.median(description_l),
|
||||
"p90": np.percentile(description_l, 90), "p95": np.percentile(description_l, 95)
|
||||
},
|
||||
"keywords": {
|
||||
"mean": np.mean(keywords_l), "median": np.median(keywords_l),
|
||||
"p90": np.percentile(keywords_l, 90), "p95": np.percentile(keywords_l, 95)
|
||||
},
|
||||
"display_name_and_keywords": {
|
||||
"mean": np.mean(display_name_and_keywords_l), "median": np.median(display_name_and_keywords_l),
|
||||
"p90": np.percentile(display_name_and_keywords_l, 90), "p95": np.percentile(display_name_and_keywords_l, 95)
|
||||
},
|
||||
"display_name_and_description": {
|
||||
"mean": np.mean(display_name_and_description_l), "median": np.median(display_name_and_description_l),
|
||||
"p90": np.percentile(display_name_and_description_l, 90), "p95": np.percentile(display_name_and_description_l, 95)
|
||||
},
|
||||
"combined": {
|
||||
"mean": np.mean(combined_l), "median": np.median(combined_l),
|
||||
"p90": np.percentile(combined_l, 90), "p95": np.percentile(combined_l, 95)
|
||||
},
|
||||
"lexical_only": {
|
||||
"mean": np.mean(lexical_only_l), "median": np.median(lexical_only_l),
|
||||
"p90": np.percentile(lexical_only_l, 90), "p95": np.percentile(lexical_only_l, 95)
|
||||
},
|
||||
"hybrid": {
|
||||
"mean": np.mean(hybrid_l), "median": np.median(hybrid_l),
|
||||
"p90": np.percentile(hybrid_l, 90), "p95": np.percentile(hybrid_l, 95)
|
||||
}
|
||||
}
|
||||
|
||||
# Save full report to json
|
||||
report_json_path = current_dir / "evaluation_report.json"
|
||||
with open(report_json_path, "w", encoding="utf-8") as f:
|
||||
json.dump({"summary": summary, "results": results}, f, indent=2, ensure_ascii=False)
|
||||
print(f"\nSaved detailed JSON report to {report_json_path}")
|
||||
|
||||
# Generate and save markdown report
|
||||
md_report_path = current_dir / "evaluation_report.md"
|
||||
md_content = f"""# Vector Search Configuration Latency Report
|
||||
Generated on: {time.strftime('%Y-%m-%d %H:%M:%S')}
|
||||
|
||||
This report documents the latency breakdown for different Elasticsearch query configurations across 520 queries, measuring flat vector searches, nested searches, multi-field combinations, pure lexical searches, and full hybrid queries.
|
||||
|
||||
## Latency Summary Table (ms)
|
||||
|
||||
| Query Configuration | Mean | Median | p90 | p95 |
|
||||
| :--- | :---: | :---: | :---: | :---: |
|
||||
| **Embedding Encode** | {summary["encode"]["mean"]:.2f} | {summary["encode"]["median"]:.2f} | {summary["encode"]["p90"]:.2f} | {summary["encode"]["p95"]:.2f} |
|
||||
| **Pure Lexical Search (`multi_match`)** | {summary["lexical_only"]["mean"]:.2f} | {summary["lexical_only"]["median"]:.2f} | {summary["lexical_only"]["p90"]:.2f} | {summary["lexical_only"]["p95"]:.2f} |
|
||||
| **Description Only (`description_vector`)** | {summary["description"]["mean"]:.2f} | {summary["description"]["median"]:.2f} | {summary["description"]["p90"]:.2f} | {summary["description"]["p95"]:.2f} |
|
||||
| **Display Name Only (`display_name_vector`)** | {summary["display_name"]["mean"]:.2f} | {summary["display_name"]["median"]:.2f} | {summary["display_name"]["p90"]:.2f} | {summary["display_name"]["p95"]:.2f} |
|
||||
| **Keywords Only (`keyword_vectors` - Nested)** | {summary["keywords"]["mean"]:.2f} | {summary["keywords"]["median"]:.2f} | {summary["keywords"]["p90"]:.2f} | {summary["keywords"]["p95"]:.2f} |
|
||||
| **Display Name & Description** | {summary["display_name_and_description"]["mean"]:.2f} | {summary["display_name_and_description"]["median"]:.2f} | {summary["display_name_and_description"]["p90"]:.2f} | {summary["display_name_and_description"]["p95"]:.2f} |
|
||||
| **Display Name & Keywords (Nested)** | {summary["display_name_and_keywords"]["mean"]:.2f} | {summary["display_name_and_keywords"]["median"]:.2f} | {summary["display_name_and_keywords"]["p90"]:.2f} | {summary["display_name_and_keywords"]["p95"]:.2f} |
|
||||
| **Combined (All 3 vector fields)** | {summary["combined"]["mean"]:.2f} | {summary["combined"]["median"]:.2f} | {summary["combined"]["p90"]:.2f} | {summary["combined"]["p95"]:.2f} |
|
||||
| **Hybrid Search (Lexical + All 3 vector fields)** | {summary["hybrid"]["mean"]:.2f} | {summary["hybrid"]["median"]:.2f} | {summary["hybrid"]["p90"]:.2f} | {summary["hybrid"]["p95"]:.2f} |
|
||||
|
||||
---
|
||||
|
||||
## 💡 Latency Bottleneck & Configuration Analysis
|
||||
|
||||
1. **Lexical Baseline**: **Pure Lexical Search** has extremely low latency (mean: **{summary["lexical_only"]["mean"]:.2f} ms**), representing standard BM25 keyword matching speed.
|
||||
2. **Impact of Nested Fields**:
|
||||
- Compares **Keywords Only (Nested)** (mean: **{summary["keywords"]["mean"]:.2f} ms**) with **Description Only (Flat)** (mean: **{summary["description"]["mean"]:.2f} ms**).
|
||||
- Combining Display Name with the flat Description (**Display Name & Description**: **{summary["display_name_and_description"]["mean"]:.2f} ms**) is faster than combining Display Name with nested Keywords (**Display Name & Keywords**: **{summary["display_name_and_keywords"]["mean"]:.2f} ms**), demonstrating that nested vector joins add a steady latency premium.
|
||||
3. **Compound Parallel Execution**:
|
||||
- Adding lexical queries to the 3 combined vector queries (**Hybrid Search**: **{summary["hybrid"]["mean"]:.2f} ms**) introduces virtually no latency overhead compared to **Combined** vector-only search (mean: **{summary["combined"]["mean"]:.2f} ms**), proving that standard lexical match is executed concurrently with HNSW vector retrieval.
|
||||
"""
|
||||
with open(md_report_path, "w", encoding="utf-8") as f:
|
||||
f.write(md_content)
|
||||
print(f"Saved Markdown report summary to {md_report_path}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(evaluate())
|
||||
@@ -0,0 +1,392 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Professional evaluation pipeline to benchmark different Sentence Transformer models
|
||||
on the OpenAlex topics dataset. Measures Information Retrieval (IR) metrics,
|
||||
Taxonomy Clustering metrics, and operational performance metrics.
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
import json
|
||||
import time
|
||||
import argparse
|
||||
import random
|
||||
from pathlib import Path
|
||||
import httpx
|
||||
import numpy as np
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Add service/src/main to python path to load settings
|
||||
current_dir = Path(__file__).parent.resolve()
|
||||
project_root = current_dir.parent.parent.resolve()
|
||||
env_path = project_root / "service" / "src" / "main" / "inse" / ".env"
|
||||
load_dotenv(dotenv_path=env_path)
|
||||
|
||||
sys.path.append(str(project_root / "service" / "src" / "main"))
|
||||
from inse.config import settings
|
||||
|
||||
ELASTIC_URL = settings.elasticsearch_url
|
||||
API_KEY = settings.elasticsearch_api_key
|
||||
|
||||
# Import evaluation libraries
|
||||
from sentence_transformers import SentenceTransformer
|
||||
from sentence_transformers.evaluation import InformationRetrievalEvaluator
|
||||
from sklearn.cluster import KMeans
|
||||
from sklearn import metrics
|
||||
|
||||
DEFAULT_MODELS = [
|
||||
"paraphrase-multilingual-mpnet-base-v2",
|
||||
"BAAI/bge-m3",
|
||||
"google/embeddinggemma-300m",
|
||||
"intfloat/multilingual-e5-small",
|
||||
"intfloat/multilingual-e5-base",
|
||||
"intfloat/multilingual-e5-large",
|
||||
"sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2",
|
||||
#english
|
||||
"sentence-transformers/all-MiniLM-L6-v2",
|
||||
"intfloat/e5-large-v2",
|
||||
"BAAI/bge-large-en-v1.5"
|
||||
]
|
||||
|
||||
def fetch_all_topics():
|
||||
topics = []
|
||||
size = 1000
|
||||
offset = 0
|
||||
headers = {
|
||||
"Authorization": f"ApiKey {API_KEY}",
|
||||
"Content-Type": "application/json"
|
||||
}
|
||||
|
||||
with httpx.Client(timeout=60.0) as client:
|
||||
while True:
|
||||
payload = {
|
||||
"query": {"match_all": {}},
|
||||
"from": offset,
|
||||
"size": size
|
||||
}
|
||||
resp = client.post(
|
||||
f"{ELASTIC_URL.rstrip('/')}/openalex-topics/_search",
|
||||
json=payload,
|
||||
headers=headers
|
||||
)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
hits = data.get("hits", {}).get("hits", [])
|
||||
if not hits:
|
||||
break
|
||||
topics.extend(hits)
|
||||
offset += len(hits)
|
||||
print(f"Fetched {len(topics)} topics...")
|
||||
if len(hits) < size:
|
||||
break
|
||||
|
||||
print(f"Total topics loaded: {len(topics)}")
|
||||
return topics
|
||||
|
||||
def prepare_data(topics, sample_size=None):
|
||||
"""
|
||||
Formulate the IR dataset and clustering taxonomy ground truth labels.
|
||||
"""
|
||||
corpus = {}
|
||||
queries = {}
|
||||
relevant_docs = {}
|
||||
|
||||
# Clustering labels
|
||||
topic_ids = []
|
||||
names_for_clustering = []
|
||||
descriptions_for_clustering = []
|
||||
labels_subfield = []
|
||||
labels_field = []
|
||||
labels_domain = []
|
||||
|
||||
# Build complete corpus dictionary of documents
|
||||
for t in topics:
|
||||
source = t["_source"]
|
||||
doc_id = source["id"]
|
||||
display_name = source.get("display_name") or ""
|
||||
description = source.get("description") or ""
|
||||
doc_text = f"{display_name} {description}".strip()
|
||||
|
||||
corpus[doc_id] = doc_text
|
||||
|
||||
# Taxonomy labels
|
||||
topic_ids.append(doc_id)
|
||||
names_for_clustering.append(display_name.strip())
|
||||
descriptions_for_clustering.append(description.strip())
|
||||
labels_subfield.append(source.get("subfield", {}).get("id") or "unknown_subfield")
|
||||
labels_field.append(source.get("field", {}).get("id") or "unknown_field")
|
||||
labels_domain.append(source.get("domain", {}).get("id") or "unknown_domain")
|
||||
|
||||
sampled_topics = topics
|
||||
if sample_size and sample_size < len(topics):
|
||||
print(f"Sampling {sample_size} topics for query/keyword generation...")
|
||||
sampled_topics = random.sample(topics, sample_size)
|
||||
|
||||
query_count = 0
|
||||
for t in sampled_topics:
|
||||
source = t["_source"]
|
||||
doc_id = source["id"]
|
||||
keywords = source.get("keywords") or []
|
||||
|
||||
for keyword in keywords:
|
||||
if not keyword.strip():
|
||||
continue
|
||||
query_id = f"q_{query_count}"
|
||||
queries[query_id] = keyword
|
||||
|
||||
# Ground truth relevant documents: topic name
|
||||
rel_docs = {doc_id}
|
||||
relevant_docs[query_id] = rel_docs
|
||||
query_count += 1
|
||||
|
||||
print(f"Dataset Formulated: {len(corpus)} corpus documents, {len(queries)} queries.")
|
||||
|
||||
return {
|
||||
"corpus": corpus,
|
||||
"queries": queries,
|
||||
"relevant_docs": relevant_docs,
|
||||
"clustering": {
|
||||
"ids": topic_ids,
|
||||
"names": names_for_clustering,
|
||||
"descriptions": descriptions_for_clustering,
|
||||
"subfield": labels_subfield,
|
||||
"field": labels_field,
|
||||
"domain": labels_domain
|
||||
}
|
||||
}
|
||||
|
||||
def evaluate_model(model_name, data, output_dir):
|
||||
"""
|
||||
Load a model, measure operational speed, and calculate IR + clustering quality.
|
||||
"""
|
||||
model_safe_name = model_name.replace("/", "_").replace("-", "_")
|
||||
report_file = output_dir / f"model_report_{model_safe_name}.json"
|
||||
|
||||
print(f"\n==================================================")
|
||||
print(f"Evaluating Model: '{model_name}'")
|
||||
print(f"==================================================")
|
||||
|
||||
start_load = time.time()
|
||||
try:
|
||||
model = SentenceTransformer(model_name)
|
||||
except Exception as exc:
|
||||
print(f"ERROR: Failed to load model '{model_name}': {exc}")
|
||||
return None
|
||||
|
||||
load_time = time.time() - start_load
|
||||
print(f"Model loaded in {load_time:.2f} seconds.")
|
||||
|
||||
num_params = sum(p.numel() for p in model.parameters())
|
||||
param_count_m = num_params / 1_000_000
|
||||
vector_dim = model.get_sentence_embedding_dimension()
|
||||
print(f"Parameters: {param_count_m:.1f}M, Vector Dimension: {vector_dim}")
|
||||
|
||||
# --- FIXED: Perform a warm-up to initialize computation graphs ---
|
||||
print("Warming up model...")
|
||||
_ = model.encode(["warmup sentence"])
|
||||
|
||||
# 2. Measure Query Latency
|
||||
sample_queries = list(data["queries"].values())[:100]
|
||||
if not sample_queries:
|
||||
sample_queries = ["artificial intelligence", "machine learning"]
|
||||
|
||||
start_lat = time.time()
|
||||
for q in sample_queries:
|
||||
_ = model.encode(q)
|
||||
latency_ms = ((time.time() - start_lat) / len(sample_queries)) * 1000
|
||||
print(f"Average Query Latency: {latency_ms:.2f} ms")
|
||||
|
||||
# 3. Measure Ingestion Throughput
|
||||
sample_docs = list(data["corpus"].values())[:200]
|
||||
start_batch = time.time()
|
||||
_ = model.encode(sample_docs, batch_size=32)
|
||||
batch_time = time.time() - start_batch
|
||||
throughput_docs_sec = len(sample_docs) / batch_time
|
||||
print(f"Ingestion Throughput: {throughput_docs_sec:.2f} docs/sec")
|
||||
|
||||
# 4. Information Retrieval Evaluation
|
||||
print("Running Information Retrieval evaluation (NDCG, MRR, Recall)...")
|
||||
|
||||
# --- FIXED: Use precision_recall_at_k for true recall metrics ---
|
||||
evaluator = InformationRetrievalEvaluator(
|
||||
data["queries"],
|
||||
data["corpus"],
|
||||
data["relevant_docs"], # The evaluator natively accepts sets, no need to cast to lists
|
||||
name=model_safe_name,
|
||||
mrr_at_k=[10],
|
||||
ndcg_at_k=[10],
|
||||
precision_recall_at_k=[10] # This ensures true Recall is calculated across multiple sibling matches
|
||||
)
|
||||
|
||||
ir_results = evaluator(model)
|
||||
|
||||
# Extract keys safely
|
||||
ndcg_key = f"{model_safe_name}_cosine_ndcg@10"
|
||||
mrr_key = f"{model_safe_name}_cosine_mrr@10"
|
||||
recall_key = f"{model_safe_name}_cosine_recall@10" # Changed from accuracy to recall
|
||||
|
||||
ndcg_score = ir_results.get(ndcg_key, 0.0)
|
||||
mrr_score = ir_results.get(mrr_key, 0.0)
|
||||
recall_score = ir_results.get(recall_key, 0.0)
|
||||
|
||||
print(f"NDCG@10: {ndcg_score:.4f}, MRR@10: {mrr_score:.4f}, Recall@10: {recall_score:.4f}")
|
||||
|
||||
# 5. Clustering evaluation against ground-truth taxonomy
|
||||
print("Running Taxonomy Clustering evaluation (NMI)...")
|
||||
|
||||
unique_subfields = list(set(data["clustering"]["subfield"]))
|
||||
n_clusters = len(unique_subfields)
|
||||
|
||||
# Topic Names Clustering
|
||||
print("Clustering Topic Names...")
|
||||
clustering_names = data["clustering"]["names"]
|
||||
name_embeddings = model.encode(clustering_names, show_progress_bar=False, batch_size=64)
|
||||
|
||||
nmi_name = 0.0
|
||||
ari_name = 0.0
|
||||
if n_clusters > 1 and len(name_embeddings) > n_clusters:
|
||||
kmeans_name = KMeans(n_clusters=n_clusters, random_state=42, n_init='auto')
|
||||
assignments_name = kmeans_name.fit_predict(name_embeddings)
|
||||
nmi_name = metrics.normalized_mutual_info_score(data["clustering"]["subfield"], assignments_name)
|
||||
ari_name = metrics.adjusted_rand_score(data["clustering"]["subfield"], assignments_name)
|
||||
print(f"Names - Subfield Clustering NMI: {nmi_name:.4f}, ARI: {ari_name:.4f}")
|
||||
|
||||
# Topic Descriptions Clustering
|
||||
print("Clustering Topic Descriptions...")
|
||||
clustering_descs = data["clustering"]["descriptions"]
|
||||
desc_embeddings = model.encode(clustering_descs, show_progress_bar=False, batch_size=64)
|
||||
|
||||
nmi_desc = 0.0
|
||||
ari_desc = 0.0
|
||||
if n_clusters > 1 and len(desc_embeddings) > n_clusters:
|
||||
kmeans_desc = KMeans(n_clusters=n_clusters, random_state=42, n_init='auto')
|
||||
assignments_desc = kmeans_desc.fit_predict(desc_embeddings)
|
||||
nmi_desc = metrics.normalized_mutual_info_score(data["clustering"]["subfield"], assignments_desc)
|
||||
ari_desc = metrics.adjusted_rand_score(data["clustering"]["subfield"], assignments_desc)
|
||||
print(f"Descriptions - Subfield Clustering NMI: {nmi_desc:.4f}, ARI: {ari_desc:.4f}")
|
||||
|
||||
report = {
|
||||
"model_name": model_name,
|
||||
"parameters_m": param_count_m,
|
||||
"vector_dim": vector_dim,
|
||||
"latency_ms": latency_ms,
|
||||
"throughput_docs_sec": throughput_docs_sec,
|
||||
"ndcg_at_10": ndcg_score,
|
||||
"mrr_at_10": mrr_score,
|
||||
"recall_at_10": recall_score,
|
||||
"name_nmi": nmi_name,
|
||||
"name_ari": ari_name,
|
||||
"desc_nmi": nmi_desc,
|
||||
"desc_ari": ari_desc
|
||||
}
|
||||
|
||||
with open(report_file, "w", encoding="utf-8") as f:
|
||||
json.dump(report, f, indent=2, ensure_ascii=False)
|
||||
print(f"Saved model report to {report_file}")
|
||||
|
||||
return report
|
||||
|
||||
def generate_consolidated_report(output_dir, reports):
|
||||
if not reports:
|
||||
print("No reports to consolidate.")
|
||||
return
|
||||
|
||||
report_file = output_dir / "model_evaluation_report.md"
|
||||
print(f"\nCompiling consolidated report into {report_file}...")
|
||||
|
||||
sorted_reports = sorted(reports, key=lambda x: x["ndcg_at_10"], reverse=True)
|
||||
|
||||
lines = [
|
||||
"# Sentence Transformer Model Evaluation Report",
|
||||
"",
|
||||
"This report aggregates performance metrics and accuracy benchmarks for different Sentence Transformer models evaluated against the OpenAlex topic keywords dataset.",
|
||||
"",
|
||||
"## Overall Leaderboard",
|
||||
"",
|
||||
"| Rank | Model Name | Vector Dim | Params (M) | Query Latency (ms) | Throughput (docs/s) | NDCG@10 | MRR@10 | Recall@10 | Name NMI | Desc NMI |",
|
||||
"| :--- | :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |"
|
||||
]
|
||||
|
||||
for idx, r in enumerate(sorted_reports):
|
||||
name_nmi = r.get("name_nmi", 0.0)
|
||||
desc_nmi = r.get("desc_nmi", 0.0)
|
||||
lines.append(
|
||||
f"| {idx+1} | `{r['model_name']}` | {r['vector_dim']} | {r['parameters_m']:.1f}M | {r['latency_ms']:.2f}ms | {r['throughput_docs_sec']:.1f} | **{r['ndcg_at_10']:.4f}** | {r['mrr_at_10']:.4f} | {r['recall_at_10']:.4f} | {name_nmi:.4f} | {desc_nmi:.4f} |"
|
||||
)
|
||||
|
||||
lines.extend([
|
||||
"",
|
||||
"### Metric Definitions:",
|
||||
"* **NDCG@10**: Normalized Discounted Cumulative Gain. Measures how well the query maps to the target topic at the top 10 positions.",
|
||||
"* **MRR@10**: Mean Reciprocal Rank. Looks at the average of `1 / rank` for the first correctly matched topic.",
|
||||
"* **Recall@10**: Percentage of times the target document (excluding sibling topics) was successfully retrieved in the top 10.",
|
||||
"* **Name NMI**: Normalized Mutual Information of K-Means clusters of topic display names against ground truth OpenAlex subfields.",
|
||||
"* **Desc NMI**: Normalized Mutual Information of K-Means clusters of topic descriptions against ground truth OpenAlex subfields.",
|
||||
"* **Query Latency**: Time to encode a single search keyword.",
|
||||
"* **Throughput**: Ingestion batch encoding speed."
|
||||
])
|
||||
|
||||
with open(report_file, "w", encoding="utf-8") as f:
|
||||
f.write("\n".join(lines))
|
||||
print(f"Report compiled successfully at {report_file}")
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description="Evaluate Sentence Transformer models on OpenAlex topics.")
|
||||
parser.add_argument("--model", type=str, help="Specific model to evaluate (skips others).")
|
||||
parser.add_argument("--sample-size", type=int, help="Sample size of topics to evaluate keywords for (faster run).")
|
||||
parser.add_argument("--all", action="store_true", help="Evaluate all topics/keywords (default if sample-size omitted).")
|
||||
parser.add_argument("--output-dir", type=str, help="Custom directory to save reports.")
|
||||
parser.add_argument("--force-refresh", action="store_true", help="Force reload topics from Elasticsearch instead of cache.")
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
if Path("/data").is_dir():
|
||||
data_dir = Path("/data")
|
||||
else:
|
||||
project_root = Path(__file__).parent.parent.parent.parent.parent.resolve()
|
||||
data_dir = project_root / "service" / "src" / "data"
|
||||
data_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
output_dir = Path(args.output_dir) if args.output_dir else data_dir
|
||||
output_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
cache_file = data_dir / "raw_topics_cache.json"
|
||||
if cache_file.exists() and not args.force_refresh:
|
||||
print(f"Loading topics from local cache: {cache_file}")
|
||||
with open(cache_file, "r", encoding="utf-8") as f:
|
||||
topics = json.load(f)
|
||||
else:
|
||||
topics = fetch_all_topics()
|
||||
with open(cache_file, "w", encoding="utf-8") as f:
|
||||
json.dump(topics, f, indent=2, ensure_ascii=False)
|
||||
print(f"Cached {len(topics)} topics to {cache_file}")
|
||||
|
||||
if not topics:
|
||||
print("Error: No topics dataset available. Make sure Elasticsearch is running or cache exists.")
|
||||
sys.exit(1)
|
||||
|
||||
data = prepare_data(topics, sample_size=args.sample_size)
|
||||
|
||||
models_to_evaluate = DEFAULT_MODELS
|
||||
if args.model:
|
||||
models_to_evaluate = [args.model]
|
||||
|
||||
print(f"Models scheduled for evaluation: {models_to_evaluate}")
|
||||
|
||||
reports = []
|
||||
for m in models_to_evaluate:
|
||||
model_safe_name = m.replace("/", "_").replace("-", "_")
|
||||
report_file = output_dir / f"model_report_{model_safe_name}.json"
|
||||
|
||||
if report_file.exists() and not args.model:
|
||||
print(f"Loading cached evaluation report for '{m}' from {report_file}")
|
||||
with open(report_file, "r", encoding="utf-8") as f:
|
||||
reports.append(json.load(f))
|
||||
else:
|
||||
rep = evaluate_model(m, data, output_dir)
|
||||
if rep:
|
||||
reports.append(rep)
|
||||
|
||||
generate_consolidated_report(output_dir, reports)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,159 @@
|
||||
# Performance Summary
|
||||
|
||||
520 Keywords as query against hybrid & semantic search
|
||||
|
||||
- Search fields:
|
||||
- display name (Keyword & single vector)
|
||||
- description (Keyword & single vector)
|
||||
- keywords (Keyword & nested vectors)
|
||||
|
||||
- 26 Fields: 20 examples each
|
||||
| # | OpenAlex Field Name | Complete Test Queries |
|
||||
|---|---------------------|-----------------------------------------|
|
||||
| 01 | **Social Sciences** | `sociology, gender inequality in workplace, urbanization trends, political polarization, human rights law, social mobility, qualitative research methods, demographic shifts, cultural anthropology, criminal justice reform, public policy analysis, indigenous languages, voter behavior, globalization effects, community development, media studies, social movements, migration patterns, welfare systems, family dynamics` |
|
||||
| 02 | **Medicine** | `cardiology, diabetes management, oncology treatment options, clinical trials, pediatric care, chronic pain relief, cardiovascular disease prevention, surgical procedures, infectious disease outbreak, medical imaging techniques, hypertension guidelines, patient outcomes, immunotherapy for cancer, epidemiology study, stroke rehabilitation, genetic disorders, telemedicine adoption, internal medicine, diagnostic accuracy, palliative care` |
|
||||
| 03 | **Engineering** | `civil engineering, structural integrity, aerospace propulsion, mechanical design, robotics automation, geotechnical analysis, bridge construction, renewable energy grid, fluid mechanics, electrical circuits, thermodynamics applications, manufacturing optimization, control systems engineering, materials fatigue, hvac design, biomedical devices, transportation infrastructure, signal processing, solid mechanics, industrial engineering` |
|
||||
| 04 | **Computer Science** | `machine learning, natural language processing, cybersecurity protocols, cloud computing architecture, neural networks, database optimization, software engineering practices, computer vision algorithms, blockchain technology, artificial intelligence ethics, human computer interaction, operating systems, distributed ledgers, compiler design, data mining techniques, cryptographic keys, quantum computing algorithms, web development frameworks, reinforcement learning, graph databases` |
|
||||
| 05 | **Arts and Humanities** | `art history, literary criticism, philosophy of mind, renaissance architecture, linguistics morphology, creative writing, musical composition, theater history, postmodern literature, ethics and morality, historical archives, film analysis, religious studies, classical archaeology, metaphysics, cultural heritage preservation, comparative literature, linguistic semantics, medieval art, epistemology` |
|
||||
| 06 | **Biochemistry, Genetics and Molecular Biology** | `dna replication, crispr gene editing, protein folding, rna sequencing, enzyme kinetics, cellular signaling pathways, metabolic pathways, genomic sequencing, molecular cloning, apoptosis mechanism, mitochondrial DNA, epigenetic modifications, proteomics analysis, gene expression regulation, chromatin remodeling, amino acid synthesis, nucleic acids, cellular differentiation, lipid metabolism, transcription factors` |
|
||||
| 07 | **Agricultural and Biological Sciences** | `crop yield optimization, plant physiology, marine biology, soil microbiology, entomology study, botany research, sustainable agriculture, animal behavior, ecology systems, pest management, forestry conservation, photosynthesis mechanism, biodiversity preservation, aquaculture techniques, agronomy practices, seed germination, horticulture science, wildlife ecology, plant pathology, livestock breeding` |
|
||||
| 08 | **Environmental Science** | `climate change mitigation, renewable resource management, air pollution monitoring, microplastics in oceans, deforestation rates, waste management systems, carbon footprint reduction, biodiversity loss, global warming impacts, ecosystem restoration, water quality analysis, urban sustainability, environmental impact assessment, glacier melting, conservation biology, greenhouse gas emissions, soil erosion control, renewable energy transition, climate adaptation strategies, acid rain causes` |
|
||||
| 09 | **Business, Management and Accounting** | `corporate strategy, supply chain logistics, financial auditing, marketing analytics, human resource management, organizational behavior, consumer behavior trends, risk assessment framework, entrepreneurship ecosystems, project management methodologies, accounting principles, brand equity, leadership styles, business ethics, digital transformation strategy, operations management, corporate governance, market segmentation, strategic planning, financial reporting standards` |
|
||||
| 10 | **Psychology** | `cognitive behavioral therapy, developmental psychology, social anxiety disorder, memory retention techniques, neuropsychology assessment, human behavior analysis, mental health counseling, personality traits theory, child development stages, addiction recovery mechanisms, emotional intelligence, perception and sensation, group dynamics psychology, depression treatment outcomes, stress management interventions, motivation theories, cognitive dissonance, behavioral psychology, mindfulness practices, sleep disorders psychology` |
|
||||
| 11 | **Materials Science** | `nanomaterials synthesis, graphene applications, polymers characterization, metallurgy engineering, semiconductor fabrication, composite materials design, biomaterials tissue engineering, thin film deposition, corrosion resistance, superconductors properties, ceramic engineering, alloy development, material degradation, photovoltaic materials, mechanical testing of alloys, smart materials technology, crystal structure analysis, carbon nanotubes research, thermal conductivity materials, magnetic materials applications` |
|
||||
| 12 | **Economics, Econometrics and Finance** | `macroeconomic policy, econometric modeling, financial market analysis, monetary theory, microeconomics principles, game theory applications, inflation rates forecast, labor economics, behavioral finance, portfolio optimization, international trade agreements, fiscal policy impact, time series analysis, asset pricing models, poverty reduction strategies, economic growth models, corporate finance theory, cryptocurrency economics, market equilibrium, public finance management` |
|
||||
| 13 | **Health Professions** | `physical therapy techniques, occupational therapy interventions, speech language pathology, radiologic technology, emergency medical services, healthcare administration, audiology assessments, rehabilitation sciences, clinical nutrition, paramedic protocols, respiratory therapy management, health informatics systems, dietetics practice, patient care quality, medical laboratory technology, orthotics and prosthetics, interprofessional healthcare collaboration, community health education, sports medicine rehabilitation, physician assistant training` |
|
||||
| 14 | **Physics and Astronomy** | `quantum mechanics, astrophysics research, dark matter detection, particle physics collision, general relativity theory, cosmology evolution, exoplanet discovery, nuclear fusion energy, condensed matter physics, string theory concepts, optics and photonics, black hole thermodynamics, gravitational waves detection, statistical mechanics, plasma physics applications, stellar evolution models, high energy physics, quantum entanglement experiments, spectroscopy techniques, thermodynamics principles` |
|
||||
| 15 | **Chemistry** | `organic synthesis, analytical chemistry methods, inorganic compounds coordination, physical chemistry thermodynamics, spectroscopy chemical analysis, catalysis mechanism design, polymer chemistry polymerization, electrochemistry batteries, medicinal chemistry design, chromatography separation techniques, chemical kinetics reactions, mass spectrometry profiling, computational chemistry modeling, environmental chemistry monitoring, photochemistry solar conversion, biophysical chemistry structure, green chemistry principles, molecular orbital theory, supramolecular architecture, crystallography structure determination` |
|
||||
| 16 | **Mathematics** | `linear algebra, differential equations solution, algebraic topology, number theory cryptography, calculus fundamentals, probability and statistics, discrete mathematics structures, numerical analysis algorithms, complex analysis functions, geometry axiom theories, combinatorics counting techniques, mathematical modeling simulation, set theory foundations, graph theory applications, real analysis limits, partial differential equations, abstract algebra groups, optimization theory algorithms, stochastic processes modeling, chaos theory dynamics` |
|
||||
| 17 | **Neuroscience** | `synaptic plasticity, neurodegenerative diseases mechanisms, brain mapping fmri, cognitive neuroscience memory, neurotransmitter receptors pathways, neural network architecture, behavioral neuroscience addiction, neurogenesis adult brain, axon guidance development, spinal cord injury, sensory processing systems, motor control pathways, alzheimer disease pathology, parkinson motor deficits, neuroimmunology inflammation, sleep neural circuits, epilepsy seizure mechanisms, computational neuroscience models, neuropharmacology drugs action, brain computer interface` |
|
||||
| 18 | **Decision Sciences** | `operations research optimization, decision analysis models, multi criteria decision making, game theory strategies, risk analysis management, linear programming applications, forecasting methods business, supply chain optimization, stochastic modeling systems, queuing theory performance, decision tree classification, predictive analytics framework, statistical decision theory, heuristic search optimization, inventory control models, simulation optimization methods, behavioral decision making, utility theory choices, data driven decision support, dynamic programming problems` |
|
||||
| 19 | **Earth and Planetary Sciences** | `plate tectonics geology, seismology earthquake prediction, volcanology eruption monitoring, paleoclimatology proxy data, planetary geology mars, mineralogy crystal structures, sedimentology deposition environments, stratigraphy rock layers, geomorphology landscape evolution, hydrology water cycle, meteorology weather forecasting, oceanography ocean currents, geochemistry isotopic analysis, remote sensing earth, petrology rock formation, impact cratering planetary, paleontology fossil records, glaciology ice sheets, geophysics magnetic fields, environmental geology hazards` |
|
||||
| 20 | **Immunology and Microbiology** | `t cell activation, antibody response mechanics, bacterial resistance antibiotics, viral replication cycle, autoimmune disease pathogenesis, innate immunity defense, vaccine development strategies, microbiome gut health, macrophage polarization function, pathogen virulence factors, cytokine storm response, mycology fungal infections, parasitology host interaction, adaptive immune system, antigen presentation pathway, bacteriophage therapy applications, immunotherapy cancer treatment, microbial biofilms formation, virology host defense, inflammation signaling pathways` |
|
||||
| 21 | **Energy** | `solar cell efficiency, wind turbine aerodynamics, battery energy storage, hydrogen fuel cells, nuclear power generation, biofuel production technologies, geothermal energy extraction, energy grid optimization, fossil fuel alternative, hydroelectric power systems, energy efficiency buildings, carbon capture storage, renewable energy policy, smart grid infrastructure, tidal energy conversion, thermal energy storage, power electronics converters, microgrid energy systems, biomass combustion processes, energy consumption forecasting` |
|
||||
| 22 | **Pharmacology, Toxicology and Pharmaceutics** | `drug delivery systems, pharmacokinetics modeling analysis, pharmacodynamics receptor binding, toxicology safety assessment, pharmaceutical formulation design, bioavailability drug absorption, cytotoxicity assays testing, clinical pharmacology trials, neuropharmacology drug effects, cardiotoxicity drug evaluation, nanoparticle drug carriers, pharmacogenomics personalized medicine, drug metabolism enzymes, adverse drug reactions, controlled release tablets, heavy metal toxicology, target identification drug, natural product pharmacology, dosage form optimization, endocrine disruptors toxicology` |
|
||||
| 23 | **Nursing** | `patient care management, nursing education curriculum, clinical nursing practice, geriatric nursing care, pediatric nursing interventions, critical care nursing, palliative nursing care, nursing leadership styles, community health nursing, evidence based nursing, mental health nursing, maternal newborn nursing, wound care management, nurse practitioner roles, patient safety protocols, nursing burnout prevention, oncology nursing practices, chronic disease management, telehealth nursing care, infection control nursing` |
|
||||
| 24 | **Chemical Engineering** | `process systems engineering, chemical reactor design, transport phenomena fluid, separation processes distillation, catalytic reaction engineering, bioprocess engineering fermentation, thermodynamics chemical mixtures, heat exchanger network, polymer processing extrusion, mass transfer operations, process safety management, fluidized bed reactor, chemical plant optimization, multi phase flow, computational fluid dynamics, industrial scale synthesis, green chemical engineering, adsorption separation kinetics, process control loops, materials processing chemical` |
|
||||
| 25 | **Dentistry** | `endodontic treatment procedures, periodontal disease therapy, orthodontic alignment techniques, dental implant surgery, prosthodontics crown design, pediatric dentistry prevention, oral maxillofacial surgery, dental caries prevention, restorative dentistry materials, oral pathology diagnosis, laser dentistry applications, dental biomaterials wear, cone beam ct, salivary diagnostics biomarkers, aesthetic dentistry veneers, root canal morphology, gingival recession treatment, fluoride treatment efficacy, dental pulp stem cells, temporomandibular joint disorders` |
|
||||
| 26 | **Veterinary** | `veterinary medicine diagnosis, canine parvovirus treatment, feline leukemia virus, equine sports medicine, bovine mastitis control, veterinary surgery techniques, animal nutrition guidelines, zoonotic disease transmission, veterinary oncology treatment, avian medicine care, small animal internal, livestock herd health, veterinary pharmacology drugs, animal welfare assessment, veterinary radiology imaging, feline behavior issues, canine hip dysplasia, veterinary epidemiology outbreaks, companion animal care, exotic pet medicine` |
|
||||
|
||||
## Latency results
|
||||
|
||||
| Query Configuration | Mean | Median | p95 |
|
||||
| :-------------------------------------- | :---: | :----: | :---: |
|
||||
| **Embedding Encode** | 35.81 | 35.11 | 42.98 |
|
||||
| **Pure Lexical Search (`multi_match`)** | 44.03 | 43.21 | 52.12 |
|
||||
|
||||
|
|
||||
| **Description Only (`description_vector`)** | 27.11 | 24.83 | 40.23 |
|
||||
| **Display Name Only (`display_name_vector`)** | 42.71 | 45.33 | 55.51 |
|
||||
| **Keywords Only (`keyword_vectors` - Nested)** | 47.65 | 47.06 | 56.88 |
|
||||
| **Display Name & Description** | 46.62 | 49.22 | 59.43 |
|
||||
| **Display Name & Keywords (Nested)** | 52.11 | 51.36 | 61.22 |
|
||||
| **Combined (All 3 vector fields)** | 57.06 | 55.65 | 67.32 |
|
||||
|
|
||||
| **Hybrid Search (Lexical + All 3 vector fields)** | 58.65 | 57.09 | 69.10 |
|
||||
|
||||
- should query runs hybrid and semantic concurrently => nested Keyword vector search bottleneck
|
||||
- Hybrid returns more results overall due to partailly matching words in display name & Keywords
|
||||
- Query: "Cell Adhesion Molecules Research"
|
||||
- Low rank return: "Q Methodology Applications"
|
||||
- because: ["**Research** Methods", "Qualitative **Research**"] Keywords
|
||||
|
||||
- Changed k & num_candidates to 500 (fixed bug, where not all keywords were considered):
|
||||
| Query Configuration | Mean | Median | p95 |
|
||||
| :--- | :---: | :---: | :---: |
|
||||
| **Embedding Encode** | 38.25 | 37.41 | 45.48 |
|
||||
| **Pure Lexical Search (`multi_match`)** | 44.98 | 43.69 | 55.21 |
|
||||
| **Description Only (`description_vector`)** | 29.69 | 27.76 | 45.46 |
|
||||
| **Display Name Only (`display_name_vector`)** | 45.20 | 46.68 | 59.47 |
|
||||
| **Keywords Only (`keyword_vectors` - Nested)** | 50.00 | 48.89 | 60.61 |
|
||||
| **Display Name & Description** | 49.84 | 51.16 | 66.37 |
|
||||
| **Display Name & Keywords (Nested)** | 55.50 | 54.16 | 66.12 |
|
||||
| **Combined (All 3 vector fields)** | 61.81 | 59.74 | 75.30 |
|
||||
| **Hybrid Search (Lexical + All 3 vector fields)** | 63.25 | 61.05 | 76.39 |
|
||||
|
||||
# Search Score Breakdown & Weight Analysis Report
|
||||
|
||||
---
|
||||
|
||||
## Global Score Contribution
|
||||
|
||||
| Weight Component | Boost | Avg. Score Contribution | Percentage of Total Score |
|
||||
| :-------------------------------------------- | :---: | :---------------------: | :-----------------------: |
|
||||
| **Lexical Match (`multi_match`)** | 1.0 | 36.2275 | 54.31% |
|
||||
| **Title Vector (`display_name_vector`)** | 30.0 | 17.9748 | 26.95% |
|
||||
| **Description Vector (`description_vector`)** | 15.0 | 2.5502 | 3.82% |
|
||||
| **Nested Keywords (`keyword_vectors`)** | 25.0 | 9.9531 | 14.92% |
|
||||
|
||||
| After fix:
|
||||
| **Lexical Match (`multi_match`)** | 1.0 | 38.2910 | 44.79% |
|
||||
| **Title Vector (`display_name_vector`)** | 30.0 | 22.5727 | 26.40% |
|
||||
| **Description Vector (`description_vector`)** | 15.0 | 3.3518 | 3.92% |
|
||||
| **Nested Keywords (`keyword_vectors`)** | 25.0 | 21.2808 | 24.89% |
|
||||
|
||||
---
|
||||
|
||||
## Contribution Breakdown by Field
|
||||
|
||||
| Field | Avg. Score | Lexical % | Title Vector % | Description Vector % | Keywords Vector % |
|
||||
| :------------------------------------------- | :--------: | :-------: | :------------: | :------------------: | :---------------: |
|
||||
| Social Sciences | 76.10 | 42.6% | 27.0% | 6.2% | 24.2% |
|
||||
| Medicine | 71.58 | 43.9% | 26.5% | 4.1% | 25.5% |
|
||||
| Engineering | 67.73 | 43.8% | 27.6% | 3.5% | 25.2% |
|
||||
| Computer Science | 69.63 | 47.3% | 23.4% | 4.0% | 25.3% |
|
||||
| Arts and Humanities | 75.38 | 40.2% | 28.7% | 5.9% | 25.1% |
|
||||
| Biochemistry, Genetics and Molecular Biology | 64.32 | 43.5% | 26.7% | 1.6% | 28.1% |
|
||||
| Agricultural and Biological Sciences | 70.48 | 38.0% | 30.7% | 4.2% | 27.1% |
|
||||
| Environmental Science | 72.92 | 44.3% | 26.3% | 5.0% | 24.3% |
|
||||
| Business, Management and Accounting | 75.14 | 47.1% | 25.8% | 2.7% | 24.5% |
|
||||
| Psychology | 67.50 | 40.8% | 28.5% | 4.9% | 25.8% |
|
||||
| Materials Science | 75.99 | 40.4% | 28.5% | 6.4% | 24.7% |
|
||||
| Economics, Econometrics and Finance | 67.58 | 43.0% | 25.3% | 5.7% | 25.9% |
|
||||
| Health Professions | 62.96 | 41.9% | 28.4% | 3.2% | 26.5% |
|
||||
| Physics and Astronomy | 70.10 | 47.5% | 24.4% | 3.6% | 24.5% |
|
||||
| Chemistry | 73.17 | 44.6% | 26.8% | 4.2% | 24.4% |
|
||||
| Mathematics | 74.83 | 48.1% | 24.7% | 4.4% | 22.9% |
|
||||
| Neuroscience | 68.20 | 45.2% | 24.6% | 5.2% | 25.0% |
|
||||
| Decision Sciences | 67.13 | 49.5% | 23.3% | 2.4% | 24.8% |
|
||||
| Earth and Planetary Sciences | 64.59 | 41.3% | 28.9% | 2.4% | 27.3% |
|
||||
| Immunology and Microbiology | 68.62 | 44.9% | 25.7% | 3.6% | 25.9% |
|
||||
| Energy | 80.04 | 50.3% | 22.8% | 5.4% | 21.6% |
|
||||
| Pharmacology, Toxicology and Pharmaceutics | 64.61 | 45.2% | 26.1% | 2.4% | 26.2% |
|
||||
| Nursing | 75.86 | 47.8% | 26.5% | 2.8% | 22.8% |
|
||||
| Chemical Engineering | 59.12 | 48.5% | 26.0% | 1.1% | 24.4% |
|
||||
| Dentistry | 62.51 | 44.1% | 28.1% | 3.1% | 24.7% |
|
||||
| Veterinary | 53.56 | 49.2% | 26.9% | 1.9% | 22.0% |
|
||||
|
||||
---
|
||||
|
||||
## Score Breakdown Examples (Top Match per Field Sample)
|
||||
|
||||
| Field & Query | Fixed Variant Performance | Bug Variant Performance |
|
||||
| :------------------------------------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| **Social Sciences**<br>`"sociology"` | **Topic**: Emile Durkheim and Sociology<br>**Total Score**: 80.7964<br><br>• Lexical: 33.6289<br>• Title KNN: 25.3876<br>• Desc KNN: 12.1561<br>• Key KNN: 24.9897<br><br>**Keywords**:<br>• 'sociology' (0.9996)<br>• 'social conditions' (0.8254) | **Topic**: Emile Durkheim and Sociology<br>**Total Score**: 55.4088<br><br>• Lexical: 33.6289<br>• Title KNN: 0.0000<br>• Desc KNN: 12.1561<br>• Key KNN: 24.9897<br><br>**Keywords**:<br>• 'sociology' (0.9996)<br>• 'social conditions' (0.8254) |
|
||||
| **Medicine**<br>`"cardiology"` | **Topic**: Cardiomyopathy and Myosin Studies<br>**Total Score**: 62.3436<br><br>• Lexical: 0.0000<br>• Title KNN: 26.0134<br>• Desc KNN: 12.4090<br>• Key KNN: 23.9212<br><br>**Keywords**:<br>• 'Cardiomyopathies' (0.9568)<br>• 'Cardiac Imaging' (0.9192) | **Topic**: Cardiac Imaging and Diagnostics<br>**Total Score**: 27.6677<br><br>• Lexical: 0.0000<br>• Title KNN: 27.6677<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Cardiac Imaging' (0.9192)<br>• 'Myocardial Infarction' (0.8564) |
|
||||
| **Engineering**<br>`"civil engineering"` | **Topic**: Civil and Structural Engineering Research<br>**Total Score**: 97.2652<br><br>• Lexical: 60.8415<br>• Title KNN: 28.1018<br>• Desc KNN: 12.3099<br>• Key KNN: 24.8941<br><br>**Keywords**:<br>• 'Civil Engineering' (0.9958)<br>• 'Construction' (0.8388) | **Topic**: Civil and Structural Engineering Research<br>**Total Score**: 97.2652<br><br>• Lexical: 60.8415<br>• Title KNN: 28.1018<br>• Desc KNN: 12.3099<br>• Key KNN: 24.8941<br><br>**Keywords**:<br>• 'Civil Engineering' (0.9958)<br>• 'Construction' (0.8388) |
|
||||
| **Computer Science**<br>`"machine learning"` | **Topic**: Machine Learning and Algorithms<br>**Total Score**: 99.2549<br><br>• Lexical: 55.5562<br>• Title KNN: 29.2590<br>• Desc KNN: 12.5187<br>• Key KNN: 24.9693<br><br>**Keywords**:<br>• 'Machine Learning' (0.9988)<br>• 'Deep Learning' (0.9119) | **Topic**: Machine Learning and Algorithms<br>**Total Score**: 74.2856<br><br>• Lexical: 55.5562<br>• Title KNN: 29.2590<br>• Desc KNN: 12.5187<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Machine Learning' (0.9988)<br>• 'Deep Learning' (0.9119) |
|
||||
| **Arts and Humanities**<br>`"art history"` | **Topic**: Art, Politics, and Modernism<br>**Total Score**: 79.6751<br><br>• Lexical: 41.4462<br>• Title KNN: 26.8390<br>• Desc KNN: 12.2412<br>• Key KNN: 23.1472<br><br>**Keywords**:<br>• 'Contemporary Art' (0.9259)<br>• 'Art Theory' (0.8902) | **Topic**: Art History and Market Analysis<br>**Total Score**: 54.6477<br><br>• Lexical: 44.3255<br>• Title KNN: 27.6256<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Art Market' (0.8499) |
|
||||
| **Biochemistry, Genetics...**<br>`"dna replication"` | **Topic**: DNA Repair Mechanisms<br>**Total Score**: 69.5873<br><br>• Lexical: 37.9645<br>• Title KNN: 25.5676<br>• Desc KNN: 0.0000<br>• Key KNN: 21.2950<br><br>**Keywords**:<br>• 'Homologous Recombination' (0.8518) | **Topic**: DNA Repair Mechanisms<br>**Total Score**: 48.2923<br><br>• Lexical: 37.9645<br>• Title KNN: 25.5676<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Homologous Recombination' (0.8518) |
|
||||
| **Agricultural Sciences**<br>`"crop yield optimization"` | **Topic**: Crop Yield and Soil Fertility<br>**Total Score**: 86.9026<br><br>• Lexical: 72.9192<br>• Title KNN: 25.6184<br>• Desc KNN: 0.0000<br>• Key KNN: 21.9673<br><br>**Keywords**:<br>• 'Crop Management' (0.8787)<br>• 'Maize Yield' (0.8515) | **Topic**: Soil Management and Crop Yield<br>**Total Score**: 65.6488<br><br>• Lexical: 58.5754<br>• Title KNN: 26.3319<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'No-till Crop Production' (0.8136) |
|
||||
| **Environmental Science**<br>`"climate change mitigation"` | **Topic**: Climate Change, Adaptation, Migration<br>**Total Score**: 95.6090<br><br>• Lexical: 55.1717<br>• Title KNN: 24.9003<br>• Desc KNN: 12.3419<br>• Key KNN: 23.2867<br><br>**Keywords**:<br>• 'Climate Change' (0.9315) | **Topic**: Climate Change and Sustainable Development<br>**Total Score**: 72.0562<br><br>• Lexical: 52.0331<br>• Title KNN: 27.6359<br>• Desc KNN: 12.3920<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Climate Change' (0.9314)<br>• 'Environmental Policy' (0.8447) |
|
||||
| **Business & Accounting**<br>`"corporate strategy"` | **Topic**: Political Influence and Corporate Strategies<br>**Total Score**: 70.1485<br><br>• Lexical: 43.3796<br>• Title KNN: 25.4050<br>• Desc KNN: 0.0000<br>• Key KNN: 23.5512<br><br>**Keywords**:<br>• 'Business Strategy' (0.9420)<br>• 'Corporate Governance' (0.8537) | **Topic**: Corporate Management and Leadership<br>**Total Score**: 44.0634<br><br>• Lexical: 18.0385<br>• Title KNN: 26.0249<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• _None matched_ |
|
||||
| **Psychology**<br>`"cognitive behavioral therapy"` | **Topic**: Psychological Treatments and Assessments<br>**Total Score**: 74.0625<br><br>• Lexical: 33.9552<br>• Title KNN: 26.3648<br>• Desc KNN: 0.0000<br>• Key KNN: 24.8575<br><br>**Keywords**:<br>• 'Cognitive Behavioral Therapy' (0.9943)<br>• 'Rational Emotive Behavior Therapy' (0.8906) | **Topic**: Psychological Treatments and Assessments<br>**Total Score**: 74.0625<br><br>• Lexical: 33.9552<br>• Title KNN: 26.3648<br>• Desc KNN: 0.0000<br>• Key KNN: 24.8575<br><br>**Keywords**:<br>• 'Cognitive Behavioral Therapy' (0.9943)<br>• 'Rational Emotive Behavior Therapy' (0.8906) |
|
||||
| **Materials Science**<br>`"nanomaterials synthesis"` | **Topic**: Copper-based nanomaterials and applications<br>**Total Score**: 79.3170<br><br>• Lexical: 31.3198<br>• Title KNN: 25.5626<br>• Desc KNN: 12.8334<br>• Key KNN: 23.2389<br><br>**Keywords**:<br>• 'Nanostructures' (0.9296)<br>• 'Nanocrystals' (0.8989) | **Topic**: Nanoparticles: synthesis and applications<br>**Total Score**: 51.4193<br><br>• Lexical: 41.6580<br>• Title KNN: 28.1196<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Nanomaterials' (0.9593)<br>• 'Nanoparticles' (0.9017) |
|
||||
| **Economics & Finance**<br>`"macroeconomic policy"` | **Topic**: Monetary Policy and Economic Impact<br>**Total Score**: 77.2466<br><br>• Lexical: 33.6052<br>• Title KNN: 27.9601<br>• Desc KNN: 12.7554<br>• Key KNN: 23.1466<br><br>**Keywords**:<br>• 'Monetary Policy' (0.9259)<br>• 'Fiscal Policy' (0.8719) | **Topic**: Monetary Policy and Economic Impact<br>**Total Score**: 54.1000<br><br>• Lexical: 33.6052<br>• Title KNN: 27.9601<br>• Desc KNN: 12.7554<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Monetary Policy' (0.9259)<br>• 'Fiscal Policy' (0.8719) |
|
||||
| **Health Professions**<br>`"physical therapy techniques"` | **Topic**: Physical Activity and Health<br>**Total Score**: 63.6719<br><br>• Lexical: 35.4732<br>• Title KNN: 24.8417<br>• Desc KNN: 0.0000<br>• Key KNN: 21.5571<br><br>**Keywords**:<br>• 'Physical Fitness' (0.8623)<br>• 'Exercise' (0.8567) | **Topic**: Physical Education and Training Studies<br>**Total Score**: 41.6865<br><br>• Lexical: 34.0993<br>• Title KNN: 25.9162<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Physical Education' (0.8518)<br>• 'Athletic Training' (0.8386) |
|
||||
| **Physics and Astronomy**<br>`"quantum mechanics"` | **Topic**: Quantum Mechanics and Applications<br>**Total Score**: 100.0179<br><br>• Lexical: 62.6773<br>• Title KNN: 29.4806<br>• Desc KNN: 12.8902<br>• Key KNN: 23.1009<br><br>**Keywords**:<br>• 'Quantum Interpretations' (0.9240)<br>• 'Quantum Measurement' (0.9195) | **Topic**: Quantum Mechanics and Non-Hermitian Physics<br>**Total Score**: 82.1469<br><br>• Lexical: 59.7515<br>• Title KNN: 28.2917<br>• Desc KNN: 0.0000<br>• Key KNN: 24.8390<br><br>**Keywords**:<br>• 'Quantum Mechanics' (0.9936)<br>• 'Non-Hermitian Physics' (0.8265) |
|
||||
| **Chemistry**<br>`"organic synthesis"` | **Topic**: Organic Chemistry Synthesis Methods<br>**Total Score**: 93.3478<br><br>• Lexical: 51.1392<br>• Title KNN: 28.8346<br>• Desc KNN: 12.8016<br>• Key KNN: 21.2545<br><br>**Keywords**:<br>• 'Total Synthesis' (0.8502) | **Topic**: Organic Chemistry Synthesis Methods<br>**Total Score**: 72.0932<br><br>• Lexical: 51.1392<br>• Title KNN: 28.8346<br>• Desc KNN: 12.8016<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Total Synthesis' (0.8502) |
|
||||
| **Mathematics**<br>`"linear algebra"` | **Topic**: Advanced Algebra and Logic<br>**Total Score**: 69.1804<br><br>• Lexical: 21.0841<br>• Title KNN: 26.3365<br>• Desc KNN: 0.0000<br>• Key KNN: 21.7598<br><br>**Keywords**:<br>• 'MV-algebras' (0.8704)<br>• 'Algebraic Semantics' (0.8542) | **Topic**: Matrix Theory and Algorithms<br>**Total Score**: 51.1267<br><br>• Lexical: 42.7259<br>• Title KNN: 0.0000<br>• Desc KNN: 0.0000<br>• Key KNN: 24.3482<br><br>**Keywords**:<br>• 'Numerical Linear Algebra' (0.9739) |
|
||||
| **Neuroscience**<br>`"synaptic plasticity"` | **Topic**: Neuroscience and Neuropharmacology Research<br>**Total Score**: 59.8949<br><br>• Lexical: 34.7332<br>• Title KNN: 0.0000<br>• Desc KNN: 13.1294<br>• Key KNN: 24.0698<br><br>**Keywords**:<br>• 'Synaptic Plasticity' (0.9628)<br>• 'Neuronal Circuits' (0.8298) | **Topic**: Neuroscience and Neuropharmacology Research<br>**Total Score**: 59.8949<br><br>• Lexical: 34.7332<br>• Title KNN: 0.0000<br>• Desc KNN: 13.1294<br>• Key KNN: 24.0698<br><br>**Keywords**:<br>• 'Synaptic Plasticity' (0.9628)<br>• 'Neuronal Circuits' (0.8298) |
|
||||
| **Decision Sciences**<br>`"operations research optimization"` | **Topic**: Operations Management Techniques<br>**Total Score**: 72.2617<br><br>• Lexical: 45.7187<br>• Title KNN: 25.8359<br>• Desc KNN: 0.0000<br>• Key KNN: 20.3829<br><br>**Keywords**:<br>• 'Operations Management' (0.8153) | **Topic**: Management and Optimization Techniques<br>**Total Score**: 67.5272<br><br>• Lexical: 38.2684<br>• Title KNN: 27.0016<br>• Desc KNN: 0.0000<br>• Key KNN: 22.7133<br><br>**Keywords**:<br>• 'Operations Research' (0.9085) |
|
||||
| **Earth Sciences**<br>`"plate tectonics geology"` | **Topic**: Geological and Geochemical Analysis<br>**Total Score**: 81.4082<br><br>• Lexical: 47.1954<br>• Title KNN: 24.9384<br>• Desc KNN: 0.0000<br>• Key KNN: 24.0854<br><br>**Keywords**:<br>• 'Plate Tectonics' (0.9634)<br>• 'Tectonics' (0.9412) | **Topic**: Geological and Geophysical Studies<br>**Total Score**: 76.8806<br><br>• Lexical: 33.5170<br>• Title KNN: 25.9864<br>• Desc KNN: 0.0000<br>• Key KNN: 24.0846<br><br>**Keywords**:<br>• 'Plate Tectonics' (0.9634)<br>• 'Tectonic Model' (0.8970) |
|
||||
| **Immunology & Micro.**<br>`"t cell activation"` | **Topic**: T-cell and B-cell Immunology<br>**Total Score**: 101.7294<br><br>• Lexical: 58.5911<br>• Title KNN: 26.2074<br>• Desc KNN: 12.7561<br>• Key KNN: 22.2172<br><br>**Keywords**:<br>• 'Memory T Cells' (0.8887)<br>• 'TGF-ß' (0.8379) | **Topic**: T-cell and B-cell Immunology<br>**Total Score**: 79.5122<br><br>• Lexical: 58.5911<br>• Title KNN: 26.2074<br>• Desc KNN: 12.7561<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Memory T Cells' (0.8887)<br>• 'TGF-ß' (0.8379) |
|
||||
| **Energy**<br>`"solar cell efficiency"` | **Topic**: solar cell performance optimization<br>**Total Score**: 100.7331<br><br>• Lexical: 69.7479<br>• Title KNN: 28.9188<br>• Desc KNN: 12.4518<br>• Key KNN: 21.6075<br><br>**Keywords**:<br>• 'Energy Conversion Efficiency' (0.8643)<br>• 'Multijunction Solar Cells' (0.8636) | **Topic**: solar cell performance optimization<br>**Total Score**: 79.1256<br><br>• Lexical: 69.7479<br>• Title KNN: 28.9188<br>• Desc KNN: 12.4518<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Energy Conversion Efficiency' (0.8643)<br>• 'Multijunction Solar Cells' (0.8636) |
|
||||
| **Pharmacology & Tox.**<br>`"drug delivery systems"` | **Topic**: Advanced Drug Delivery Systems<br>**Total Score**: 101.0864<br><br>• Lexical: 82.7073<br>• Title KNN: 29.0884<br>• Desc KNN: 0.0000<br>• Key KNN: 23.9235<br><br>**Keywords**:<br>• 'Drug Delivery' (0.9569) | **Topic**: Advanced Drug Delivery Systems<br>**Total Score**: 77.1629<br><br>• Lexical: 82.7073<br>• Title KNN: 29.0884<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• 'Drug Delivery' (0.9569) |
|
||||
| **Nursing**<br>`"patient care management"` | **Topic**: Family and Patient Care in ICU<br>**Total Score**: 81.2835<br><br>• Lexical: 62.5713<br>• Title KNN: 25.2221<br>• Desc KNN: 0.0000<br>• Key KNN: 23.3629<br><br>**Keywords**:<br>• 'Patient-Centered Care' (0.9345)<br>• 'Critical Care' (0.8654) | **Topic**: Health Services Management and Policy<br>**Total Score**: 49.0703<br><br>• Lexical: 44.9180<br>• Title KNN: 0.0000<br>• Desc KNN: 0.0000<br>• Key KNN: 24.1204<br><br>**Keywords**:<br>• 'patient care' (0.9648)<br>• 'hospital management' (0.9044) |
|
||||
| **Chemical Engineering**<br>`"process systems engineering"` | **Topic**: Systems Engineering Methodologies<br>**Total Score**: 69.4196<br><br>• Lexical: 46.7857<br>• Title KNN: 27.1586<br>• Desc KNN: 0.0000<br>• Key KNN: 21.4144<br><br>**Keywords**:<br>• 'Interdisciplinary System Eng.' (0.8566)<br>• 'Model-Based Systems Eng.' (0.8462) | **Topic**: Control Systems in Engineering<br>**Total Score**: 48.0307<br><br>• Lexical: 30.2824<br>• Title KNN: 25.1976<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• _None matched_ |
|
||||
| **Dentistry**<br>`"endodontic treatment procedures"` | **Topic**: Endodontics and Root Canal Treatments<br>**Total Score**: 85.0595<br><br>• Lexical: 33.2248<br>• Title KNN: 27.3373<br>• Desc KNN: 12.9073<br>• Key KNN: 24.7433<br><br>**Keywords**:<br>• 'Endodontic Treatment' (0.9897)<br>• 'Regenerative Endodontics' (0.9185) | **Topic**: Endodontics and Root Canal Treatments<br>**Total Score**: 85.0595<br><br>• Lexical: 33.2248<br>• Title KNN: 27.3373<br>• Desc KNN: 12.9073<br>• Key KNN: 24.7433<br><br>**Keywords**:<br>• 'Endodontic Treatment' (0.9897)<br>• 'Regenerative Endodontics' (0.9185) |
|
||||
| **Veterinary**<br>`"veterinary medicine diagnosis"` | **Topic**: Animal health and immunology<br>**Total Score**: 70.5398<br><br>• Lexical: 36.6445<br>• Title KNN: 24.4738<br>• Desc KNN: 0.0000<br>• Key KNN: 24.6649<br><br>**Keywords**:<br>• 'Veterinary Diagnosis' (0.9866) | **Topic**: Veterinary Medicine and Surgery<br>**Total Score**: 63.5579<br><br>• Lexical: 36.3745<br>• Title KNN: 27.1833<br>• Desc KNN: 0.0000<br>• Key KNN: 0.0000<br><br>**Keywords**:<br>• _None matched_ |
|
||||
+31375
File diff suppressed because it is too large
Load Diff
+28540
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,64 @@
|
||||
# Approach
|
||||
|
||||
**NDCG@10**, **MRR@10**, **Recall@10** :
|
||||
|
||||
- Topic: Document
|
||||
- OpenAlex: "display_name": "Impact of Light on Environment and Health",
|
||||
- Keyword: Query
|
||||
- OpenAlex: "keywords": [
|
||||
"Nighttime Light Data",
|
||||
"Economic Growth",
|
||||
"Light Pollution",
|
||||
"Remote Sensing",
|
||||
"Population Mapping",
|
||||
"Urbanization Dynamics",
|
||||
"Artificial Light",
|
||||
"Satellite Imagery",
|
||||
"Poverty Prediction",
|
||||
"Ecological Impacts" ]
|
||||
|
||||
Each Keyword is searched in the Topic display name Vector space
|
||||
|
||||
# Overall Leaderboard
|
||||
|
||||
> **Note** First round is invalid
|
||||
|
||||
First round (all topics, but included sibling topics messed up metrics)
|
||||
| Rank | Model Name | Vector Dim | Params (M) | Query Latency (ms) | Throughput (docs/s) | NDCG@10 | MRR@10 | Recall@10 | Subfield NMI |
|
||||
| :--- | :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |
|
||||
| 1 | `intfloat/e5-large-v2` | 1024 | 335.1M | 96.63ms | 5.7 | **0.2304** | 0.5054 | 0.0691 | 0.5917 |
|
||||
| 2 | `BAAI/bge-large-en-v1.5` | 1024 | 335.1M | 96.24ms | 5.8 | **0.2292** | 0.4944 | 0.0691 | 0.5921 |
|
||||
| 3 | `intfloat/multilingual-e5-large` | 1024 | 559.9M | 104.13ms | 4.8 | **0.2131** | 0.4789 | 0.0636 | 0.5900 |
|
||||
| 4 | `google/embeddinggemma-300m` | 768 | 307.6M | 47.11ms | 14.0 | **0.2121** | 0.4479 | 0.0637 | 0.6054 |
|
||||
| 5 | `intfloat/multilingual-e5-base` | 768 | 278.0M | 29.11ms | 16.3 | **0.2100** | 0.4641 | 0.0620 | 0.5919 |
|
||||
| 6 | `intfloat/multilingual-e5-small` | 384 | 117.7M | 12.15ms | 55.3 | **0.2021** | 0.4446 | 0.0594 | 0.5880 |
|
||||
| 7 | `BAAI/bge-m3` | 1024 | 567.8M | 96.92ms | 4.8 | **0.1879** | 0.4219 | 0.0544 | 0.5929 |
|
||||
| 8 | `paraphrase-multilingual-mpnet-base-v2` | 768 | 278.0M | 29.65ms | 17.0 | **0.1792** | 0.3565 | 0.0520 | 0.6010 |
|
||||
| 9 | `sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2` | 384 | 117.7M | 12.12ms | 58.1 | **0.1748** | 0.3494 | 0.0514 | 0.5940 |
|
||||
|
||||
Second adjusted round (500 topics sample size)(seperated clustering into name and description fields)
|
||||
| Rank | Model Name | Vector Dim | Params (M) | Query Latency (ms) | Throughput (docs/s) | NDCG@10 | MRR@10 | Recall@10 | Name NMI | Desc NMI |
|
||||
| :--- | :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: |
|
||||
| 1 | `intfloat/e5-large-v2` | 1024 | 335.1M | 101.71ms | 5.6 | **0.4261** | 0.3797 | 0.5758 | 0.5254 | 0.5947 |
|
||||
| 2 | `BAAI/bge-large-en-v1.5` | 1024 | 335.1M | 98.38ms | 5.6 | **0.4084** | 0.3628 | 0.5546 | 0.5591 | 0.5961 |
|
||||
| 3 | `intfloat/multilingual-e5-large` | 1024 | 559.9M | 111.27ms | 4.8 | **0.3956** | 0.3501 | 0.5424 | 0.5171 | 0.5845 |
|
||||
| 4 | `intfloat/multilingual-e5-base` | 768 | 278.0M | 28.86ms | 17.9 | **0.3807** | 0.3357 | 0.5256 | 0.5374 | 0.5851 |
|
||||
| 5 | `google/embeddinggemma-300m` | 768 | 307.6M | 45.55ms | 15.7 | **0.3558** | 0.3121 | 0.4976 | 0.5485 | 0.6148 |
|
||||
| 6 | `intfloat/multilingual-e5-small` | 384 | 117.7M | 11.74ms | 57.6 | **0.3531** | 0.3050 | 0.5078 | 0.5450 | 0.5914 |
|
||||
| 7 | `sentence-transformers/all-MiniLM-L6-v2` | 384 | 22.7M | 7.07ms | 117.0 | **0.3471** | 0.3034 | 0.4882 | 0.5636 | 0.5936 |
|
||||
| 8 | `BAAI/bge-m3` | 1024 | 567.8M | 96.19ms | 4.9 | **0.3221** | 0.2829 | 0.4484 | 0.5246 | 0.5885 |
|
||||
| 9 | `sentence-transformers/paraphrase-multilingual-MiniLM-L12-v2` | 384 | 117.7M | 12.63ms | 58.0 | **0.2350** | 0.2005 | 0.3468 | 0.5544 | 0.5984 |
|
||||
| 10 | `paraphrase-multilingual-mpnet-base-v2` | 768 | 278.0M | 24.67ms | 22.2 | **0.2347** | 0.1999 | 0.3480 | 0.5638 | 0.6043 |
|
||||
Baseline with all topics for second round:
|
||||
| Rank | Model Name | Vector Dim | Params (M) | Query Latency (ms) | Throughput (docs/s) | NDCG@10 | MRR@10 | Recall@10 | Name NMI | Desc NMI |
|
||||
| 1 | `intfloat/multilingual-e5-base` | 768 | 278.0M | 32.83ms | 16.5 | **0.3751** | 0.3290 | 0.5234 | 0.5374 | 0.5851 |
|
||||
|
||||
## Metric Definitions:
|
||||
|
||||
- **NDCG@10**: Normalized Discounted Cumulative Gain. Measures how well the query maps to the target topic at the top 10 positions.
|
||||
- **MRR@10**: Mean Reciprocal Rank. Looks at the average of `1 / rank` for the first correctly matched topic.
|
||||
- **Recall@10**: Percentage of times the target document (excluding sibling topics) was successfully retrieved in the top 10.
|
||||
- **Name NMI**: Normalized Mutual Information of K-Means clusters of topic display names against ground truth OpenAlex subfields.
|
||||
- **Desc NMI**: Normalized Mutual Information of K-Means clusters of topic descriptions against ground truth OpenAlex subfields.
|
||||
- **Query Latency**: Time to encode a single search keyword.
|
||||
- **Throughput**: Ingestion batch encoding speed.
|
||||
@@ -12,6 +12,11 @@ ELASTICSEARCH_API_KEY=am1wWXBaMEJEVWJoZkE5MnBaUlk6TWlvbW1LRlMzNjdDUHgzYmVkUmI5UQ
|
||||
ELASTICSEARCH_INSE_URL=https://inse.nes.uni-due.de/elastic
|
||||
ELASTICSEARCH_INSE_API_KEY=bG1NSWc1NEJPZ3FnTGZCZXRSSEg6VnJXRFd5SnpSTTNWc1VPT01FMEhMZw==
|
||||
|
||||
# Debugging: Log every outgoing Elasticsearch query (index + payload)
|
||||
PRINT_ES_QUERIES=false
|
||||
# Debugging: Log the duration of every Elasticsearch request
|
||||
PRINT_ES_TIMINGS=true
|
||||
|
||||
# Sentence Transformers Configuration
|
||||
SENTENCE_TRANSFORMERS_MODEL_NAME=intfloat/multilingual-e5-base
|
||||
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
import datetime
|
||||
import logging
|
||||
from datetime import timedelta
|
||||
|
||||
from inse.authors.v2.model import (
|
||||
CollaborationGraph,
|
||||
CollaborationGraphJob,
|
||||
CollaborationGraphStatus,
|
||||
)
|
||||
from sqlmodel import Session, select
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
JOB_RETENTION = timedelta(hours=1)
|
||||
|
||||
|
||||
def create_collaboration_graph_job(session: Session, graph_id: str) -> None:
|
||||
"""Creates a new collaboration graph job in the database.
|
||||
|
||||
Args:
|
||||
session (Session): The SQLModel session to use for database operations.
|
||||
graph_id (str): The ID of the collaboration graph for which to create a job.
|
||||
"""
|
||||
existing = session.get(CollaborationGraphJob, graph_id)
|
||||
if existing:
|
||||
logger.info(f"Job for graph_id {graph_id} already exists.")
|
||||
return
|
||||
job = CollaborationGraphJob(
|
||||
graph_id=graph_id, status=CollaborationGraphStatus.PENDING
|
||||
)
|
||||
session.add(job)
|
||||
session.commit()
|
||||
|
||||
|
||||
def get_collaboration_graph_job(
|
||||
session: Session, graph_id: str
|
||||
) -> CollaborationGraphJob | None:
|
||||
"""Retrieves a collaboration graph job from the database by its graph ID.
|
||||
|
||||
Args:
|
||||
session (Session): The SQLModel session to use for database operations.
|
||||
graph_id (str): The ID of the collaboration graph for which to retrieve the job.
|
||||
|
||||
Returns:
|
||||
CollaborationGraphJob | None: The collaboration graph job if found, otherwise None.
|
||||
"""
|
||||
return session.get(CollaborationGraphJob, graph_id)
|
||||
|
||||
|
||||
def mark_collaboration_graph_job_completed(
|
||||
session: Session, graph_id: str, result: CollaborationGraph
|
||||
) -> None:
|
||||
"""Marks a collaboration graph job as completed and stores the result.
|
||||
|
||||
Args:
|
||||
session (Session): The SQLModel session to use for database operations.
|
||||
graph_id (str): The ID of the collaboration graph for which to mark the job as completed.
|
||||
result (CollaborationGraph): The result of the collaboration graph generation.
|
||||
"""
|
||||
job = get_collaboration_graph_job(session, graph_id)
|
||||
if not job:
|
||||
logger.warning(
|
||||
f"No job found for graph_id {graph_id}. Cannot mark as completed."
|
||||
)
|
||||
return
|
||||
job.status = CollaborationGraphStatus.COMPLETED
|
||||
job.set_result(result)
|
||||
job.updated_at = datetime.datetime.now(datetime.timezone.utc)
|
||||
session.add(job)
|
||||
session.commit()
|
||||
|
||||
|
||||
def mark_collaboration_graph_job_failed(
|
||||
session: Session, graph_id: str, error_message: str
|
||||
) -> None:
|
||||
"""Marks a collaboration graph job as failed and stores the error message.
|
||||
|
||||
Args:
|
||||
session (Session): The SQLModel session to use for database operations.
|
||||
graph_id (str): The ID of the collaboration graph for which to mark the job as failed.
|
||||
error_message (str): The error message describing the failure.
|
||||
"""
|
||||
job = get_collaboration_graph_job(session, graph_id)
|
||||
if not job:
|
||||
logger.warning(f"No job found for graph_id {graph_id}. Cannot mark as failed.")
|
||||
return
|
||||
job.status = CollaborationGraphStatus.FAILED
|
||||
job.error_message = error_message
|
||||
job.updated_at = datetime.datetime.now(datetime.timezone.utc)
|
||||
session.add(job)
|
||||
session.commit()
|
||||
|
||||
|
||||
def cleanup_old_collaboration_graph_jobs(
|
||||
session: Session, max_age: timedelta = JOB_RETENTION
|
||||
) -> int:
|
||||
"""Cleans up old collaboration graph jobs that are older than the retention period.
|
||||
|
||||
Args:
|
||||
session (Session): The SQLModel session to use for database operations.
|
||||
max_age (timedelta): The maximum age of jobs to retain.
|
||||
|
||||
Returns:
|
||||
int: The number of stale jobs that were cleaned up.
|
||||
"""
|
||||
cutoff_time = datetime.datetime.now(datetime.timezone.utc) - max_age
|
||||
statement = select(CollaborationGraphJob).where(
|
||||
CollaborationGraphJob.created_at < cutoff_time
|
||||
)
|
||||
stale_jobs = session.exec(statement).all()
|
||||
count = len(stale_jobs)
|
||||
for job in stale_jobs:
|
||||
session.delete(job)
|
||||
session.commit()
|
||||
if count:
|
||||
logger.debug("Cleaned up %d stale collaboration graph jobs", count)
|
||||
return count
|
||||
@@ -1,7 +1,187 @@
|
||||
from datetime import datetime
|
||||
from enum import StrEnum
|
||||
|
||||
from inse.model import Page
|
||||
from inse.models.openalex.author import Author
|
||||
from pydantic import BaseModel
|
||||
from sqlmodel import Field, SQLModel
|
||||
|
||||
|
||||
class AuthorPage(Page[Author]):
|
||||
"""A paginated response containing a list of authors."""
|
||||
|
||||
|
||||
class MatchMode(StrEnum):
|
||||
AND = "and"
|
||||
OR = "or"
|
||||
|
||||
|
||||
class GraphFilterType(StrEnum):
|
||||
PUBLICATION_FILTERED = "publication_filtered"
|
||||
COLLABORATOR_FILTERED = "collaborator_filtered"
|
||||
|
||||
|
||||
class AuthorNode(BaseModel):
|
||||
id: str = Field(description="The ID of the author.")
|
||||
display_name: str = Field(description="The display name of the author.")
|
||||
institution_ids: list[str] = Field(
|
||||
default_factory=list,
|
||||
description="IDs of institutions this author is affiliated with.",
|
||||
)
|
||||
|
||||
|
||||
class WorkNode(BaseModel):
|
||||
id: str = Field(description="The ID of the work.")
|
||||
display_name: str = Field(description="The title of the work.")
|
||||
publication_year: int = Field(description="The publication year of the work.")
|
||||
author_ids: list[str] = Field(
|
||||
default_factory=list,
|
||||
description="IDs of authors who contributed to this work.",
|
||||
)
|
||||
|
||||
|
||||
class InstitutionNode(BaseModel):
|
||||
id: str = Field(description="The ID of the institution.")
|
||||
display_name: str = Field(description="The display name of the institution.")
|
||||
|
||||
|
||||
class Edge(BaseModel):
|
||||
source: str = Field(description="The ID of the source node.")
|
||||
target: str = Field(description="The ID of the target node.")
|
||||
weight: float = Field(description="The weight of the edge.")
|
||||
|
||||
|
||||
class InternalCollaborationGraph(BaseModel):
|
||||
root_author_id: str = Field(description="The ID of the root author.")
|
||||
authors: dict[str, AuthorNode] = Field(default_factory=dict)
|
||||
institutions: dict[str, InstitutionNode] = Field(default_factory=dict)
|
||||
works: dict[str, WorkNode] = Field(default_factory=dict)
|
||||
edges: list[Edge] = Field(
|
||||
default_factory=list,
|
||||
description="Person-to-person collaboration edges only.",
|
||||
)
|
||||
|
||||
def add_author(
|
||||
self, author: AuthorNode, institution_ids: list[str] | None = None
|
||||
) -> None:
|
||||
existing = self.authors.get(author.id)
|
||||
if existing is None:
|
||||
author.institution_ids = list(dict.fromkeys(institution_ids or []))
|
||||
self.authors[author.id] = author
|
||||
elif institution_ids:
|
||||
merged = dict.fromkeys(existing.institution_ids)
|
||||
merged.update(dict.fromkeys(institution_ids))
|
||||
existing.institution_ids = list(merged)
|
||||
|
||||
def add_institution(self, institution: InstitutionNode) -> None:
|
||||
self.institutions.setdefault(institution.id, institution)
|
||||
|
||||
def add_work(self, work: WorkNode, author_ids: list[str] | None = None) -> None:
|
||||
existing = self.works.get(work.id)
|
||||
if existing is None:
|
||||
work.author_ids = list(dict.fromkeys(author_ids or []))
|
||||
self.works[work.id] = work
|
||||
elif author_ids:
|
||||
merged = dict.fromkeys(existing.author_ids)
|
||||
merged.update(dict.fromkeys(author_ids))
|
||||
existing.author_ids = list(merged)
|
||||
|
||||
def add_edge(self, edge: Edge) -> None:
|
||||
self.edges.append(edge)
|
||||
|
||||
|
||||
class CollaborationGraph(BaseModel):
|
||||
root_author_id: str = Field(description="The ID of the root author.")
|
||||
authors: list[AuthorNode] = Field(
|
||||
default_factory=list, description="A list of author nodes."
|
||||
)
|
||||
institutions: list[InstitutionNode] = Field(
|
||||
default_factory=list, description="A list of institution nodes."
|
||||
)
|
||||
works: list[WorkNode] = Field(
|
||||
default_factory=list, description="A list of work nodes."
|
||||
)
|
||||
edges: list[Edge] = Field(
|
||||
default_factory=list, description="A list of edges in the collaboration graph."
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def from_internal_graph(
|
||||
cls, internal_graph: InternalCollaborationGraph, min_edge_weight: float = 2.0
|
||||
) -> "CollaborationGraph":
|
||||
return cls(
|
||||
root_author_id=internal_graph.root_author_id,
|
||||
authors=list(internal_graph.authors.values()),
|
||||
institutions=list(internal_graph.institutions.values()),
|
||||
works=list(internal_graph.works.values()),
|
||||
edges=_collapse_edges(internal_graph.edges, min_weight=min_edge_weight),
|
||||
)
|
||||
|
||||
|
||||
def _collapse_edges(edges: list[Edge], min_weight: float = 2.0) -> list[Edge]:
|
||||
reduced: dict[frozenset[str], Edge] = {}
|
||||
|
||||
for edge in edges:
|
||||
key = frozenset((edge.source, edge.target))
|
||||
existing = reduced.get(key)
|
||||
if existing is None:
|
||||
reduced[key] = Edge(
|
||||
source=edge.source, target=edge.target, weight=edge.weight
|
||||
)
|
||||
else:
|
||||
existing.weight += edge.weight
|
||||
|
||||
return [edge for edge in reduced.values() if edge.weight >= min_weight]
|
||||
|
||||
|
||||
class CollaborationGraphStatus(StrEnum):
|
||||
PENDING = "pending"
|
||||
COMPLETED = "completed"
|
||||
FAILED = "failed"
|
||||
|
||||
|
||||
class StartCollaborationGraphResponse(BaseModel):
|
||||
graph_id: str = Field(description="The ID of the collaboration graph.")
|
||||
|
||||
|
||||
class CollaborationGraphStatusResponse(BaseModel):
|
||||
status: CollaborationGraphStatus = Field(
|
||||
description="The status of the collaboration graph."
|
||||
)
|
||||
result: CollaborationGraph | None = Field(
|
||||
default=None, description="The collaboration graph result if completed."
|
||||
)
|
||||
error_message: str | None = Field(
|
||||
default=None, description="The error message if the graph generation failed."
|
||||
)
|
||||
|
||||
|
||||
class CollaborationGraphJob(SQLModel, table=True):
|
||||
__tablename__ = "collaboration_graph_jobs" # type: ignore
|
||||
|
||||
graph_id: str = Field(
|
||||
primary_key=True,
|
||||
description="The ID of the collaboration graph generation task.",
|
||||
)
|
||||
status: CollaborationGraphStatus = Field(
|
||||
default=CollaborationGraphStatus.PENDING,
|
||||
description="The status of the collaboration graph generation task.",
|
||||
)
|
||||
result: str | None = Field(
|
||||
default=None,
|
||||
description="The JSON-serialized result of the collaboration graph generation task.",
|
||||
)
|
||||
error_message: str | None = Field(
|
||||
default=None,
|
||||
description="The error message if the collaboration graph generation failed.",
|
||||
)
|
||||
created_at: datetime = Field(default_factory=datetime.utcnow)
|
||||
updated_at: datetime = Field(default_factory=datetime.utcnow)
|
||||
|
||||
def get_result(self) -> "CollaborationGraph | None":
|
||||
if self.result is None:
|
||||
return None
|
||||
return CollaborationGraph.model_validate_json(self.result)
|
||||
|
||||
def set_result(self, value: BaseModel | None) -> None:
|
||||
self.result = value.model_dump_json() if value is not None else None
|
||||
|
||||
@@ -2,8 +2,14 @@ import logging
|
||||
from typing import Annotated
|
||||
|
||||
import inse.authors.v2.service as authors_service
|
||||
from fastapi import APIRouter, Query
|
||||
from inse.authors.v2.model import AuthorPage
|
||||
from fastapi import APIRouter, BackgroundTasks, Path, Query
|
||||
from inse.authors.v2.model import (
|
||||
AuthorPage,
|
||||
CollaborationGraphStatusResponse,
|
||||
StartCollaborationGraphResponse,
|
||||
)
|
||||
from inse.database import SessionDep
|
||||
from inse.models.openalex.author import Author
|
||||
from inse.router_prefixes import RouterPrefixes
|
||||
from inse.tags import Tags
|
||||
|
||||
@@ -13,6 +19,22 @@ logger = logging.getLogger(__name__)
|
||||
router = APIRouter(prefix=RouterPrefixes.AUTHORS_V2, tags=[Tags.AUTHORS_V2])
|
||||
|
||||
|
||||
@router.get(
|
||||
"/{raw_oa_author_id}",
|
||||
operation_id="getAuthorById",
|
||||
summary="Returns an author for a given author ID.",
|
||||
)
|
||||
async def get_author_by_id(
|
||||
raw_oa_author_id: Annotated[
|
||||
str,
|
||||
Path(description="The ID of the author to retrieve."),
|
||||
],
|
||||
) -> Author:
|
||||
return await authors_service.get_author_by_id_strict_or_raise(
|
||||
raw_oa_author_id=raw_oa_author_id
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/authors/id",
|
||||
operation_id="getAuthorsByIds",
|
||||
@@ -41,3 +63,86 @@ async def autocomplete_authors_for_selector(
|
||||
] = "",
|
||||
) -> AuthorPage:
|
||||
return await authors_service.autocomplete_authors_for_selector(query=query)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/collaboration-graph",
|
||||
operation_id="startCollaborationGraph",
|
||||
summary="Returns a collaboration graph for a given author ID.",
|
||||
)
|
||||
def start_collaboration_graph(
|
||||
session: SessionDep,
|
||||
background_tasks: BackgroundTasks,
|
||||
raw_oa_author_id: Annotated[
|
||||
str,
|
||||
Query(
|
||||
description="The raw OpenAlex author ID for which to retrieve the collaboration graph."
|
||||
),
|
||||
],
|
||||
year_from: Annotated[
|
||||
int | None,
|
||||
Query(
|
||||
description="The starting year to filter the works by (optional).",
|
||||
),
|
||||
] = None,
|
||||
year_to: Annotated[
|
||||
int | None,
|
||||
Query(
|
||||
description="The ending year to filter the works by (optional).",
|
||||
),
|
||||
] = None,
|
||||
min_collaborators: Annotated[
|
||||
int | None,
|
||||
Query(
|
||||
description="The minimum number of collaborators to filter the works by (optional).",
|
||||
),
|
||||
] = None,
|
||||
max_collaborators: Annotated[
|
||||
int | None,
|
||||
Query(
|
||||
description="The maximum number of collaborators to filter the works by (optional).",
|
||||
),
|
||||
] = None,
|
||||
topic_ids: Annotated[
|
||||
list[str] | None,
|
||||
Query(
|
||||
description="A list of topic IDs to filter the works by (optional).",
|
||||
),
|
||||
] = None,
|
||||
institution_ids: Annotated[
|
||||
list[str] | None,
|
||||
Query(
|
||||
description="A list of institution IDs to filter the works by (optional).",
|
||||
),
|
||||
] = None,
|
||||
) -> StartCollaborationGraphResponse:
|
||||
return authors_service.start_collaboration_graph(
|
||||
session=session,
|
||||
background_tasks=background_tasks,
|
||||
raw_oa_author_id=raw_oa_author_id,
|
||||
year_from=year_from,
|
||||
year_to=year_to,
|
||||
min_collaborators=min_collaborators,
|
||||
max_collaborators=max_collaborators,
|
||||
topic_ids=topic_ids,
|
||||
institution_ids=institution_ids,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/collaboration-graph/{graph_id}/status",
|
||||
operation_id="getCollaborationGraphStatus",
|
||||
summary="Returns the status of a collaboration graph generation task.",
|
||||
)
|
||||
def get_collaboration_graph_status(
|
||||
session: SessionDep,
|
||||
graph_id: Annotated[
|
||||
str,
|
||||
Path(
|
||||
description="The ID of the collaboration graph generation task.",
|
||||
),
|
||||
],
|
||||
) -> CollaborationGraphStatusResponse:
|
||||
return authors_service.get_collaboration_graph_status(
|
||||
session=session, graph_id=graph_id
|
||||
)
|
||||
|
||||
@@ -1,10 +1,31 @@
|
||||
import logging
|
||||
|
||||
import inse.works.v2.service as works_service
|
||||
from fastapi import BackgroundTasks
|
||||
from inse.authors.institution_membership_query import (
|
||||
build_active_institution_membership_query,
|
||||
)
|
||||
from inse.authors.v2.model import AuthorPage
|
||||
from inse.authors.v2 import collaboration_graph_jobs
|
||||
from inse.authors.v2.model import (
|
||||
AuthorNode,
|
||||
AuthorPage,
|
||||
CollaborationGraph,
|
||||
CollaborationGraphStatus,
|
||||
CollaborationGraphStatusResponse,
|
||||
InstitutionNode,
|
||||
InternalCollaborationGraph,
|
||||
MatchMode,
|
||||
StartCollaborationGraphResponse,
|
||||
WorkNode,
|
||||
)
|
||||
from inse.exceptions import NotFoundException
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESIndex
|
||||
from inse.models.openalex.author import Author
|
||||
from inse.works.v2.model import WorkPageV2
|
||||
from sqlmodel import Session
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def search_authors(
|
||||
@@ -48,21 +69,41 @@ async def search_authors(
|
||||
return AuthorPage(elements=authors, total=len(authors), page=page, size=size)
|
||||
|
||||
|
||||
async def get_author_by_id(author_id: str) -> Author | None:
|
||||
async def get_author_by_id(raw_oa_author_id: str) -> Author | None:
|
||||
"""Retrieves an author from the OpenAlex Elasticsearch index based on the provided author ID.
|
||||
|
||||
Args:
|
||||
author_id (str): The ID of the author to retrieve.
|
||||
raw_oa_author_id (str): The raw OpenAlex author ID of the author to retrieve.
|
||||
|
||||
Returns:
|
||||
Optional[Author]: The retrieved author, or None if not found.
|
||||
"""
|
||||
response = await elasticsearch.get(index=ESIndex.OPENALEX_AUTHORS, doc_id=author_id)
|
||||
response = await elasticsearch.get(
|
||||
index=ESIndex.OPENALEX_AUTHORS, doc_id=raw_oa_author_id
|
||||
)
|
||||
if not response.get("found"):
|
||||
return None
|
||||
return Author.from_dict(response.get("_source", {})) # type: ignore
|
||||
|
||||
|
||||
async def get_author_by_id_strict_or_raise(raw_oa_author_id: str) -> Author:
|
||||
"""Retrieves an author from the OpenAlex Elasticsearch index based on the provided author ID.
|
||||
|
||||
Args:
|
||||
raw_oa_author_id (str): The raw OpenAlex author ID of the author to retrieve.
|
||||
|
||||
Returns:
|
||||
Author: The retrieved author.
|
||||
|
||||
Raises:
|
||||
ValueError: If the author is not found.
|
||||
"""
|
||||
author = await get_author_by_id(raw_oa_author_id=raw_oa_author_id)
|
||||
if not author:
|
||||
raise NotFoundException(f"Author with ID {raw_oa_author_id} not found.")
|
||||
return author
|
||||
|
||||
|
||||
async def autocomplete_authors_for_selector(query: str) -> AuthorPage:
|
||||
"""Autocompletes authors based on a search term for use in a selector component.
|
||||
|
||||
@@ -154,3 +195,524 @@ async def authors_currently_belong_to_institution(
|
||||
source=["id"],
|
||||
)
|
||||
return {author.id for author in authors.elements if author.id}
|
||||
|
||||
|
||||
def _build_collaboration_graph_query(
|
||||
raw_oa_author_id: str,
|
||||
year_from: int | None = None,
|
||||
year_to: int | None = None,
|
||||
min_collaborators: int | None = None,
|
||||
max_collaborators: int | None = None,
|
||||
topic_ids: list[str] | None = None,
|
||||
topic_match_mode: MatchMode = MatchMode.OR,
|
||||
institution_ids: list[str] | None = None,
|
||||
):
|
||||
"""Builds an Elasticsearch query for retrieving a collaboration graph for a given author ID, optionally filtered by year range, collaborator count, topic IDs, and institution IDs.
|
||||
|
||||
Args:
|
||||
raw_oa_author_id (str): The raw OpenAlex author ID for which to build the collaboration graph.
|
||||
year_from (int | None, optional): The starting year to filter the works by (optional). Defaults to None.
|
||||
year_to (int | None, optional): The ending year to filter the works by (optional). Defaults to None.
|
||||
min_collaborators (int | None, optional): The minimum number of collaborators to filter the works by (optional). Defaults to None.
|
||||
max_collaborators (int | None, optional): The maximum number of collaborators to filter the works by (optional). Defaults to None.
|
||||
topic_ids (list[str] | None, optional): A list of topic IDs to filter the works by (optional). Defaults to None.
|
||||
topic_match_mode (MatchMode, optional): The mode for matching topics (optional). Defaults to MatchMode.OR.
|
||||
institution_ids (list[str] | None, optional): A list of institution IDs to filter the works by (optional). Defaults to None.
|
||||
|
||||
Raises:
|
||||
ValueError: If the topic_match_mode is not valid.
|
||||
ValueError: If the topic_ids list is empty.
|
||||
ValueError: If the institution_ids list is empty.
|
||||
|
||||
Returns:
|
||||
_type_: The built Elasticsearch query for the collaboration graph.
|
||||
"""
|
||||
author_id = _prefix_id(raw_oa_author_id)
|
||||
|
||||
must: list[dict] = [
|
||||
{
|
||||
"nested": {
|
||||
"path": "authorships",
|
||||
"query": {"term": {"authorships.author.id": author_id}},
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
if year_from is not None or year_to is not None:
|
||||
range_query: dict = {}
|
||||
if year_from is not None:
|
||||
range_query["gte"] = year_from
|
||||
if year_to is not None:
|
||||
range_query["lte"] = year_to
|
||||
must.append({"range": {"publication_year": range_query}})
|
||||
|
||||
if min_collaborators is not None or max_collaborators is not None:
|
||||
range_query: dict = {}
|
||||
if min_collaborators is not None:
|
||||
range_query["gte"] = min_collaborators
|
||||
if max_collaborators is not None:
|
||||
range_query["lte"] = max_collaborators
|
||||
must.append({"range": {"authors_count": range_query}})
|
||||
|
||||
if topic_ids is not None:
|
||||
if not topic_ids:
|
||||
raise ValueError("topic_ids must be a non-empty list if provided")
|
||||
if topic_match_mode not in (MatchMode.OR, MatchMode.AND):
|
||||
raise ValueError('topic_match_mode must be "or" or "and"')
|
||||
|
||||
if topic_match_mode == MatchMode.OR:
|
||||
must.append(
|
||||
{
|
||||
"nested": {
|
||||
"path": "topics",
|
||||
"query": {"terms": {"topics.id": topic_ids}},
|
||||
}
|
||||
}
|
||||
)
|
||||
else:
|
||||
for topic_id in topic_ids:
|
||||
must.append(
|
||||
{
|
||||
"nested": {
|
||||
"path": "topics",
|
||||
"query": {"term": {"topics.id": topic_id}},
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
if institution_ids is not None:
|
||||
if not institution_ids:
|
||||
raise ValueError("institution_ids must be a non-empty list if provided")
|
||||
must.append(
|
||||
{
|
||||
"nested": {
|
||||
"path": "authorships",
|
||||
"query": {
|
||||
"nested": {
|
||||
"path": "authorships.institutions",
|
||||
"query": {
|
||||
"terms": {
|
||||
"authorships.institutions.id": institution_ids
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
query = {
|
||||
"bool": {
|
||||
"must": must,
|
||||
}
|
||||
}
|
||||
|
||||
logger.debug("Collaboration graph query for author %s: %s", raw_oa_author_id, query)
|
||||
|
||||
return query
|
||||
|
||||
|
||||
COLLABORATION_GRAPH_SOURCE_FIELDS = [
|
||||
"id",
|
||||
"display_name",
|
||||
"publication_year",
|
||||
"authors_count",
|
||||
"authorships.author.id",
|
||||
"authorships.author.display_name",
|
||||
"authorships.institutions.id",
|
||||
"authorships.institutions.display_name",
|
||||
]
|
||||
|
||||
|
||||
def _get_collaboration_graph_cache_key(
|
||||
raw_oa_author_id: str,
|
||||
year_from: int | None = None,
|
||||
year_to: int | None = None,
|
||||
min_collaborators: int | None = None,
|
||||
max_collaborators: int | None = None,
|
||||
topic_ids: list[str] | None = None,
|
||||
institution_ids: list[str] | None = None,
|
||||
) -> str:
|
||||
"""Generates a cache key for the collaboration graph based on the provided parameters.
|
||||
|
||||
Args:
|
||||
raw_oa_author_id (str): The raw OpenAlex author ID for which to generate the cache key.
|
||||
year_from (int | None, optional): The starting year to filter the works by (optional). Defaults to None.
|
||||
year_to (int | None, optional): The ending year to filter the works by (optional). Defaults to None.
|
||||
min_collaborators (int | None, optional): The minimum number of collaborators to filter the works by (optional). Defaults to None.
|
||||
max_collaborators (int | None, optional): The maximum number of collaborators to filter the works by (optional). Defaults to None.
|
||||
topic_ids (list[str] | None, optional): A list of topic IDs to filter the works by (optional). Defaults to None.
|
||||
institution_ids (list[str] | None, optional): A list of institution IDs to filter the works by (optional). Defaults to None.
|
||||
|
||||
Returns:
|
||||
str: The generated cache key.
|
||||
"""
|
||||
|
||||
return f"collaboration_graph:{raw_oa_author_id}:{year_from}:{year_to}:{min_collaborators}:{max_collaborators}:{':'.join(sorted([_remove_prefix_id(id) for id in topic_ids or []]))}:{':'.join(sorted([_remove_prefix_id(id) for id in institution_ids or []]))}"
|
||||
|
||||
|
||||
async def _build_collaboration_graph(
|
||||
raw_oa_author_id: str,
|
||||
year_from: int | None = None,
|
||||
year_to: int | None = None,
|
||||
min_collaborators: int | None = None,
|
||||
max_collaborators: int | None = None,
|
||||
topic_ids: list[str] | None = None,
|
||||
institution_ids: list[str] | None = None,
|
||||
) -> CollaborationGraph:
|
||||
"""Gets a collaboration graph for a given author ID, optionally filtered by year range, collaborator count, topic IDs, and institution IDs.
|
||||
|
||||
Args:
|
||||
raw_oa_author_id (str): The raw OpenAlex author ID for which to retrieve the collaboration graph.
|
||||
year_from (int | None, optional): The starting year to filter the works by (optional). Defaults to None.
|
||||
year_to (int | None, optional): The ending year to filter the works by (optional). Defaults to None.
|
||||
min_collaborators (int | None, optional): The minimum number of collaborators to filter the works by (optional). Defaults to None.
|
||||
max_collaborators (int | None, optional): The maximum number of collaborators to filter the works by (optional). Defaults to None.
|
||||
topic_ids (list[str] | None, optional): A list of topic IDs to filter the works by (optional). Defaults to None.
|
||||
institution_ids (list[str] | None, optional): A list of institution IDs to filter the works by (optional). Defaults to None.
|
||||
|
||||
Returns:
|
||||
CollaborationGraph: The collaboration graph for the given author ID.
|
||||
"""
|
||||
|
||||
query = _build_collaboration_graph_query(
|
||||
raw_oa_author_id=raw_oa_author_id,
|
||||
year_from=year_from,
|
||||
year_to=year_to,
|
||||
min_collaborators=min_collaborators,
|
||||
max_collaborators=max_collaborators,
|
||||
topic_ids=topic_ids,
|
||||
institution_ids=institution_ids,
|
||||
)
|
||||
logger.debug(
|
||||
f"Searching works for collaboration graph of author {raw_oa_author_id} with query: {query}"
|
||||
)
|
||||
|
||||
work_page: WorkPageV2 = await works_service._search_works(
|
||||
query=query,
|
||||
source=COLLABORATION_GRAPH_SOURCE_FIELDS,
|
||||
page=0,
|
||||
size=10000,
|
||||
sort=[{"publication_year": "desc"}, {"id": "asc"}],
|
||||
)
|
||||
|
||||
logger.debug(
|
||||
f"Retrieved {len(work_page.elements)} works for collaboration graph of author {raw_oa_author_id} (total: {work_page.total})"
|
||||
)
|
||||
|
||||
return _build_collaboration_graph_from_works(
|
||||
page=work_page, raw_oa_author_id=raw_oa_author_id
|
||||
)
|
||||
|
||||
|
||||
def _build_collaboration_graph_from_works(
|
||||
page: WorkPageV2, raw_oa_author_id: str, min_edge_weight: float = 1.0
|
||||
) -> CollaborationGraph:
|
||||
"""Builds a collaboration graph from a page of works and a raw OpenAlex author ID.
|
||||
|
||||
Args:
|
||||
page (WorkPageV2): The page of works from which to build the collaboration graph.
|
||||
raw_oa_author_id (str): The raw OpenAlex author ID for which to build the collaboration graph.
|
||||
min_edge_weight (float, optional): Minimum weight for a collaboration edge to be
|
||||
included in the result. Filters out authors who only co-authored a single
|
||||
work together. Defaults to 1.0.
|
||||
|
||||
Returns:
|
||||
CollaborationGraph: The built collaboration graph.
|
||||
"""
|
||||
works = page.elements
|
||||
internal_graph = InternalCollaborationGraph(
|
||||
root_author_id=_prefix_id(raw_oa_author_id)
|
||||
)
|
||||
|
||||
for work in works:
|
||||
if not work.id or not work.display_name or not work.publication_year:
|
||||
continue
|
||||
|
||||
work_author_ids: list[str] = []
|
||||
|
||||
for authorship in work.authorships or []:
|
||||
author = authorship.author
|
||||
if not author or not author.id or not author.display_name:
|
||||
continue
|
||||
|
||||
institution_ids: list[str] = []
|
||||
for institution in authorship.institutions or []:
|
||||
if (
|
||||
not institution
|
||||
or not institution.id
|
||||
or not institution.display_name
|
||||
):
|
||||
continue
|
||||
|
||||
internal_graph.add_institution(
|
||||
InstitutionNode(
|
||||
id=institution.id, display_name=institution.display_name
|
||||
)
|
||||
)
|
||||
institution_ids.append(institution.id)
|
||||
|
||||
internal_graph.add_author(
|
||||
AuthorNode(id=author.id, display_name=author.display_name),
|
||||
institution_ids=institution_ids,
|
||||
)
|
||||
work_author_ids.append(author.id)
|
||||
|
||||
internal_graph.add_work(
|
||||
WorkNode(
|
||||
id=work.id,
|
||||
display_name=work.display_name,
|
||||
publication_year=work.publication_year,
|
||||
),
|
||||
author_ids=work_author_ids,
|
||||
)
|
||||
|
||||
# Toggle to add edges between all pairs of authors for each work. This can create a dense graph if many authors co-author works together.
|
||||
# for author_a, author_b in combinations(sorted(set(work_author_ids)), 2):
|
||||
# internal_graph.add_edge(Edge(source=author_a, target=author_b, weight=1.0))
|
||||
|
||||
graph = CollaborationGraph.from_internal_graph(
|
||||
internal_graph, min_edge_weight=min_edge_weight
|
||||
)
|
||||
|
||||
logger.debug(
|
||||
f"Built collaboration graph for author {raw_oa_author_id}: "
|
||||
f"{len(graph.authors)} authors, {len(graph.works)} works, "
|
||||
f"{len(graph.institutions)} institutions, {len(graph.edges)} edges"
|
||||
)
|
||||
|
||||
return graph
|
||||
|
||||
|
||||
jobs: dict[str, dict] = {}
|
||||
|
||||
|
||||
def start_collaboration_graph(
|
||||
session: Session,
|
||||
background_tasks: BackgroundTasks,
|
||||
raw_oa_author_id: str,
|
||||
year_from: int | None = None,
|
||||
year_to: int | None = None,
|
||||
min_collaborators: int | None = None,
|
||||
max_collaborators: int | None = None,
|
||||
topic_ids: list[str] | None = None,
|
||||
institution_ids: list[str] | None = None,
|
||||
) -> StartCollaborationGraphResponse:
|
||||
"""Starts the process of generating a collaboration graph for a given author ID, optionally filtered by year range, collaborator count, topic IDs, and institution IDs.
|
||||
|
||||
Args:
|
||||
raw_oa_author_id (str): The raw OpenAlex author ID for which to generate the collaboration graph.
|
||||
year_from (int | None, optional): The starting year to filter the works by (optional). Defaults to None.
|
||||
year_to (int | None, optional): The ending year to filter the works by (optional). Defaults to None.
|
||||
min_collaborators (int | None, optional): The minimum number of collaborators to filter the works by (optional). Defaults to None.
|
||||
max_collaborators (int | None, optional): The maximum number of collaborators to filter the works by (optional). Defaults to None.
|
||||
topic_ids (list[str] | None, optional): A list of topic IDs to filter the works by (optional). Defaults to None.
|
||||
institution_ids (list[str] | None, optional): A list of institution IDs to filter the works by (optional). Defaults to None.
|
||||
|
||||
Returns:
|
||||
StartCollaborationGraphResponse: The response containing the cache key for the collaboration graph generation process.
|
||||
"""
|
||||
cache_key = _get_collaboration_graph_cache_key(
|
||||
raw_oa_author_id=raw_oa_author_id,
|
||||
year_from=year_from,
|
||||
year_to=year_to,
|
||||
min_collaborators=min_collaborators,
|
||||
max_collaborators=max_collaborators,
|
||||
topic_ids=topic_ids,
|
||||
institution_ids=institution_ids,
|
||||
)
|
||||
logger.debug("Generated cache key for collaboration graph: %s", cache_key)
|
||||
|
||||
existing_job = collaboration_graph_jobs.get_collaboration_graph_job(
|
||||
session, cache_key
|
||||
)
|
||||
if existing_job:
|
||||
logger.debug(
|
||||
"Collaboration graph job already exists for cache key: %s, status: %s",
|
||||
cache_key,
|
||||
existing_job.status,
|
||||
)
|
||||
return StartCollaborationGraphResponse(graph_id=cache_key)
|
||||
|
||||
collaboration_graph_jobs.create_collaboration_graph_job(session, cache_key)
|
||||
background_tasks.add_task(
|
||||
_run_collaboration_graph_job,
|
||||
session,
|
||||
cache_key,
|
||||
raw_oa_author_id,
|
||||
year_from,
|
||||
year_to,
|
||||
min_collaborators,
|
||||
max_collaborators,
|
||||
topic_ids,
|
||||
institution_ids,
|
||||
)
|
||||
|
||||
logger.debug(
|
||||
"Started background task for collaboration graph job with cache key: %s",
|
||||
cache_key,
|
||||
)
|
||||
|
||||
return StartCollaborationGraphResponse(graph_id=cache_key)
|
||||
|
||||
|
||||
async def _run_collaboration_graph_job(
|
||||
session: Session,
|
||||
cache_key: str,
|
||||
raw_oa_author_id: str,
|
||||
year_from: int | None = None,
|
||||
year_to: int | None = None,
|
||||
min_collaborators: int | None = None,
|
||||
max_collaborators: int | None = None,
|
||||
topic_ids: list[str] | None = None,
|
||||
institution_ids: list[str] | None = None,
|
||||
) -> None:
|
||||
"""Runs the collaboration graph generation job in the background and updates the job status in the jobs dictionary.
|
||||
|
||||
Args:
|
||||
cache_key (str): The cache key for the collaboration graph generation process.
|
||||
raw_oa_author_id (str): The raw OpenAlex author ID for which to generate the collaboration graph.
|
||||
year_from (int | None, optional): The starting year to filter the works by (optional). Defaults to None.
|
||||
year_to (int | None, optional): The ending year to filter the works by (optional). Defaults to None.
|
||||
min_collaborators (int | None, optional): The minimum number of collaborators to filter the works by (optional). Defaults to None.
|
||||
max_collaborators (int | None, optional): The maximum number of collaborators to filter the works by (optional). Defaults to None.
|
||||
topic_ids (list[str] | None, optional): A list of topic IDs to filter the works by (optional). Defaults to None.
|
||||
institution_ids (list[str] | None, optional): A list of institution IDs to filter the works by (optional). Defaults to None.
|
||||
"""
|
||||
try:
|
||||
result = await _build_collaboration_graph(
|
||||
raw_oa_author_id=raw_oa_author_id,
|
||||
year_from=year_from,
|
||||
year_to=year_to,
|
||||
min_collaborators=min_collaborators,
|
||||
max_collaborators=max_collaborators,
|
||||
topic_ids=topic_ids,
|
||||
institution_ids=institution_ids,
|
||||
)
|
||||
logger.debug(
|
||||
f"Collaboration graph job completed successfully for cache key: {cache_key}"
|
||||
)
|
||||
collaboration_graph_jobs.mark_collaboration_graph_job_completed(
|
||||
session, cache_key, result
|
||||
)
|
||||
logger.debug(
|
||||
f"Collaboration graph job marked as completed for cache key: {cache_key}"
|
||||
)
|
||||
except Exception as e:
|
||||
logger.exception("Collaboration graph job failed: %s", cache_key)
|
||||
collaboration_graph_jobs.mark_collaboration_graph_job_failed(
|
||||
session, cache_key, str(e)
|
||||
)
|
||||
logger.debug(
|
||||
f"Collaboration graph job marked as failed for cache key: {cache_key}, error: {e!s}"
|
||||
)
|
||||
|
||||
|
||||
def get_collaboration_graph_status(
|
||||
session: Session,
|
||||
graph_id: str,
|
||||
) -> CollaborationGraphStatusResponse:
|
||||
"""Retrieves the status of a collaboration graph generation process based on the provided graph ID.
|
||||
|
||||
Args:
|
||||
graph_id (str): The ID of the collaboration graph generation process.
|
||||
|
||||
Returns:
|
||||
CollaborationGraphStatusResponse: The response containing the status and result (if completed) of the collaboration graph generation process.
|
||||
"""
|
||||
job = collaboration_graph_jobs.get_collaboration_graph_job(session, graph_id)
|
||||
if not job:
|
||||
logger.debug("No job found for the provided graph ID: %s", graph_id)
|
||||
return CollaborationGraphStatusResponse(
|
||||
status=CollaborationGraphStatus.FAILED,
|
||||
error_message="No job found for the provided graph ID.",
|
||||
)
|
||||
logger.debug(
|
||||
"Retrieved job status for graph ID: %s, status: %s",
|
||||
graph_id,
|
||||
job.status,
|
||||
)
|
||||
|
||||
status = job.status
|
||||
result = (
|
||||
job.get_result() if job.status == CollaborationGraphStatus.COMPLETED else None
|
||||
)
|
||||
error_message = job.error_message
|
||||
if result and job.status == CollaborationGraphStatus.COMPLETED:
|
||||
if _is_graph_empty(result):
|
||||
status = CollaborationGraphStatus.FAILED
|
||||
result = None
|
||||
error_message = "Der generierte Kollaborationsgraph ist leer. Bitte versuchen Sie es mit anderen Filtereinstellungen."
|
||||
logger.debug(
|
||||
"Collaboration graph for graph ID: %s is empty, marking as failed.",
|
||||
graph_id,
|
||||
)
|
||||
elif _is_graph_too_large(result):
|
||||
status = CollaborationGraphStatus.FAILED
|
||||
result = None
|
||||
error_message = "Der generierte Kollaborationsgraph ist zu groß, um ihn anzuzeigen. Bitte versuchen Sie es mit anderen Filtereinstellungen."
|
||||
logger.debug(
|
||||
"Collaboration graph for graph ID: %s is too large, marking as failed.",
|
||||
graph_id,
|
||||
)
|
||||
|
||||
return CollaborationGraphStatusResponse(
|
||||
status=status,
|
||||
result=result,
|
||||
error_message=error_message,
|
||||
)
|
||||
|
||||
|
||||
def _is_graph_empty(graph: CollaborationGraph) -> bool:
|
||||
"""Returns True if the collaboration graph has no authors, works, or institutions.
|
||||
|
||||
Args:
|
||||
graph (CollaborationGraph): The collaboration graph to check.
|
||||
|
||||
Returns:
|
||||
bool: True if the graph is empty, False otherwise.
|
||||
"""
|
||||
return not (graph.authors or graph.works or graph.institutions)
|
||||
|
||||
|
||||
def _is_graph_too_large(graph: CollaborationGraph, max_nodes: int = 1000) -> bool:
|
||||
"""Returns True if the total number of nodes (authors, works, and institutions) in the graph exceeds the specified max_nodes limit.
|
||||
|
||||
Args:
|
||||
graph (CollaborationGraph): The collaboration graph to check.
|
||||
max_nodes (int, optional): The maximum number of nodes allowed. Defaults to 1000.
|
||||
|
||||
Returns:
|
||||
bool: True if the graph is too large, False otherwise.
|
||||
"""
|
||||
return len(graph.authors + graph.works + graph.institutions) > max_nodes
|
||||
|
||||
|
||||
def _prefix_id(raw_oa_id: str) -> str:
|
||||
"""Prefixes the raw OpenAlex ID with "https://openalex.org/" if it does not already start with that prefix.
|
||||
|
||||
Args:
|
||||
raw_oa_id (str): The raw OpenAlex ID to prefix.
|
||||
|
||||
Returns:
|
||||
str: The prefixed OpenAlex ID.
|
||||
"""
|
||||
|
||||
if not raw_oa_id.startswith("https://openalex.org/"):
|
||||
return f"https://openalex.org/{raw_oa_id}"
|
||||
return raw_oa_id
|
||||
|
||||
|
||||
def _remove_prefix_id(prefixed_oa_id: str) -> str:
|
||||
"""Removes the "https://openalex.org/" prefix from the provided OpenAlex ID if it starts with that prefix.
|
||||
|
||||
Args:
|
||||
prefixed_oa_id (str): The OpenAlex ID with the prefix to remove.
|
||||
|
||||
Returns:
|
||||
str: The OpenAlex ID without the prefix.
|
||||
"""
|
||||
|
||||
if prefixed_oa_id.startswith("https://openalex.org/"):
|
||||
return prefixed_oa_id[len("https://openalex.org/") :]
|
||||
return prefixed_oa_id
|
||||
|
||||
@@ -1,43 +0,0 @@
|
||||
from typing import Annotated, Optional
|
||||
|
||||
from fastapi import APIRouter, Body, Path, status
|
||||
|
||||
from inse.collaboration_network.schemas import (
|
||||
CollaborationNetwork,
|
||||
FilterProperties,
|
||||
)
|
||||
from inse.tags import Tags
|
||||
import inse.collaboration_network.service as collaboration_network_service
|
||||
|
||||
|
||||
router = APIRouter(
|
||||
prefix="/api/person/network", tags=[Tags.PERSON_NETWORK]
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/{raw_user_id}",
|
||||
summary="Get a person's collaboration network.",
|
||||
description="Returns a person's collaboration network based on their works and co-authors.",
|
||||
operation_id="getCollaborationNetwork",
|
||||
responses={
|
||||
status.HTTP_200_OK: {
|
||||
"description": "Successful Response",
|
||||
"model": CollaborationNetwork,
|
||||
},
|
||||
status.HTTP_404_NOT_FOUND: {"description": "Person not found"},
|
||||
},
|
||||
)
|
||||
async def get_collaboration_network(
|
||||
raw_user_id: Annotated[str, Path(description="The raw user ID of the person.")],
|
||||
filter_properties: Annotated[
|
||||
Optional[FilterProperties],
|
||||
Body(
|
||||
description="The filter properties for the collaboration network.",
|
||||
),
|
||||
] = None,
|
||||
) -> CollaborationNetwork:
|
||||
return await collaboration_network_service.get_collaboration_network(
|
||||
raw_user_id=raw_user_id,
|
||||
filter_properties=filter_properties,
|
||||
)
|
||||
@@ -1,273 +0,0 @@
|
||||
from enum import Enum
|
||||
from typing import List, Optional, Set
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from inse.models.openalex.work_topic import WorkTopic
|
||||
from inse.utils import extract_raw_topic_id
|
||||
|
||||
|
||||
class InstitutionInformation(BaseModel):
|
||||
raw_id: str = Field(
|
||||
title="Raw Institution ID",
|
||||
description="The raw institution ID of the institution.",
|
||||
)
|
||||
display_name: str = Field(
|
||||
title="Institution Display Name",
|
||||
description="The display name of the institution.",
|
||||
)
|
||||
|
||||
def __eq__(self, value: object) -> bool:
|
||||
if isinstance(value, InstitutionInformation):
|
||||
return self.raw_id == value.raw_id
|
||||
return False
|
||||
|
||||
def __hash__(self) -> int:
|
||||
return hash(self.raw_id)
|
||||
|
||||
|
||||
class WorkTopicInformation(BaseModel):
|
||||
raw_topic_id: str = Field(
|
||||
title="Topic ID",
|
||||
description="The ID of the topic.",
|
||||
)
|
||||
display_name: str = Field(
|
||||
title="Topic Name",
|
||||
description="The name of the topic.",
|
||||
)
|
||||
|
||||
def __eq__(self, value: object) -> bool:
|
||||
if isinstance(value, WorkTopicInformation):
|
||||
return self.raw_topic_id == value.raw_topic_id
|
||||
return False
|
||||
|
||||
def __hash__(self) -> int:
|
||||
return hash(self.raw_topic_id)
|
||||
|
||||
@classmethod
|
||||
def from_topic(cls, topic: WorkTopic) -> "WorkTopicInformation":
|
||||
"""Creates a WorkTopicInformation instance from a WorkTopic instance.
|
||||
|
||||
Args:
|
||||
topic (WorkTopic): The WorkTopic instance to create the WorkTopicInformation from.
|
||||
Returns:
|
||||
WorkTopicInformation: The created WorkTopicInformation instance.
|
||||
"""
|
||||
return cls(
|
||||
raw_topic_id=extract_raw_topic_id(str(topic.id)),
|
||||
display_name=str(topic.display_name),
|
||||
)
|
||||
|
||||
|
||||
class CollaborationNetworkNodeType(str, Enum):
|
||||
AUTHOR = "author"
|
||||
INSTITUTION = "institution"
|
||||
WORK = "work"
|
||||
|
||||
|
||||
class FilterInformation(BaseModel):
|
||||
min_possible_year: int = Field(
|
||||
title="Minimum Year",
|
||||
description="The minimum publication year of the works in the collaboration network.",
|
||||
)
|
||||
max_possible_year: int = Field(
|
||||
title="Maximum Year",
|
||||
description="The maximum publication year of the works in the collaboration network.",
|
||||
)
|
||||
institutions: List[InstitutionInformation] = Field(
|
||||
title="Institutions",
|
||||
description="The list of institutions associated with the works in the collaboration network.",
|
||||
)
|
||||
topics: List[WorkTopicInformation] = Field(
|
||||
title="Topics",
|
||||
description="The list of topics associated with the works in the collaboration network.",
|
||||
)
|
||||
|
||||
|
||||
class WorksFilterProperties(BaseModel):
|
||||
start_year: int = Field(
|
||||
default=0,
|
||||
title="Start Year",
|
||||
description="The start publication year for the works to include in the collaboration network.",
|
||||
)
|
||||
end_year: int = Field(
|
||||
default=9999,
|
||||
title="End Year",
|
||||
description="The end publication year for the works to include in the collaboration network.",
|
||||
)
|
||||
allowed_topics: List[str] = Field(
|
||||
default_factory=list,
|
||||
title="Allowed Topics",
|
||||
description="The list of raw topic IDs to include in the collaboration network. If empty, all topics will be included.",
|
||||
)
|
||||
min_contributors: int = Field(
|
||||
default=1,
|
||||
title="Minimum Contributors",
|
||||
description="The minimum number of contributors required for a work to be included in the collaboration network.",
|
||||
)
|
||||
max_contributors: int = Field(
|
||||
default=100,
|
||||
title="Maximum Contributors",
|
||||
description="The maximum number of contributors allowed for a work to be included in the collaboration network.",
|
||||
)
|
||||
|
||||
|
||||
class AuthorsFilterProperties(BaseModel):
|
||||
allowed_institutions: List[str] = Field(
|
||||
default_factory=list,
|
||||
title="Allowed Institutions",
|
||||
description="The list of raw institution IDs to include in the collaboration network. If empty, all institutions will be included.",
|
||||
)
|
||||
min_collaborations: int = Field(
|
||||
default=1,
|
||||
title="Minimum Collaborations",
|
||||
description="The minimum number of collaborations required for an author to be included in the collaboration network.",
|
||||
)
|
||||
max_collaborations: int = Field(
|
||||
default=1000,
|
||||
title="Maximum Collaborations",
|
||||
description="The maximum number of collaborations allowed for an author to be included in the collaboration network.",
|
||||
)
|
||||
|
||||
|
||||
class FilterProperties(BaseModel):
|
||||
filter_by: str = Field(
|
||||
default="works",
|
||||
title="Filter By",
|
||||
description="The type of filter to apply when generating the collaboration network. Can be either 'works' or 'authors'. If 'works', the filter properties in the 'works_filter_properties' field will be used. If 'authors', the filter properties in the 'authors_filter_properties' field will be used.",
|
||||
)
|
||||
works_filter_properties: Optional[WorksFilterProperties] = Field(
|
||||
title="Works Filter Properties",
|
||||
description="The filter properties to apply when filtering works for the collaboration network. This field is only applicable if the 'filter_by' field is set to 'works'.",
|
||||
)
|
||||
authors_filter_properties: Optional[AuthorsFilterProperties] = Field(
|
||||
title="Authors Filter Properties",
|
||||
description="The filter properties to apply when filtering authors for the collaboration network. This field is only applicable if the 'filter_by' field is set to 'authors'.",
|
||||
)
|
||||
|
||||
|
||||
class CollaborationNetworkNode(BaseModel):
|
||||
raw_id: str = Field(
|
||||
title="Raw ID",
|
||||
description="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.",
|
||||
)
|
||||
display_name: str = Field(
|
||||
title="Display Name", description="The display name of the node."
|
||||
)
|
||||
category: CollaborationNetworkNodeType = Field(
|
||||
title="Category",
|
||||
description="The category of the node, either 'author', 'institution', or 'work'.",
|
||||
)
|
||||
|
||||
def __eq__(self, value: object) -> bool:
|
||||
if isinstance(value, CollaborationNetworkNode):
|
||||
return self.raw_id == value.raw_id
|
||||
return False
|
||||
|
||||
def __hash__(self) -> int:
|
||||
return hash(self.raw_id)
|
||||
|
||||
|
||||
class WorkNetworkNode(CollaborationNetworkNode):
|
||||
publication_year: Optional[int] = Field(
|
||||
title="Publication Year",
|
||||
description="The publication year of the work represented by this node. This field is only applicable if the category of the node is 'work'.",
|
||||
)
|
||||
work_topics_information: Optional[Set[WorkTopicInformation]] = Field(
|
||||
title="Work Topics Information",
|
||||
description="The list of topic information associated with the work represented by this node. This field is only applicable if the category of the node is 'work'.",
|
||||
)
|
||||
|
||||
def __eq__(self, value: object) -> bool:
|
||||
if isinstance(value, WorkNetworkNode):
|
||||
return self.raw_id == value.raw_id
|
||||
return False
|
||||
|
||||
def __hash__(self) -> int:
|
||||
return hash(self.raw_id)
|
||||
|
||||
|
||||
class AuthorNetworkNode(CollaborationNetworkNode):
|
||||
def __eq__(self, value: object) -> bool:
|
||||
if isinstance(value, AuthorNetworkNode):
|
||||
return self.raw_id == value.raw_id
|
||||
return False
|
||||
|
||||
def __hash__(self) -> int:
|
||||
return hash(self.raw_id)
|
||||
|
||||
|
||||
class InstitutionNetworkNode(CollaborationNetworkNode):
|
||||
def __eq__(self, value: object) -> bool:
|
||||
if isinstance(value, InstitutionNetworkNode):
|
||||
return self.raw_id == value.raw_id
|
||||
return False
|
||||
|
||||
def __hash__(self) -> int:
|
||||
return hash(self.raw_id)
|
||||
|
||||
|
||||
class CollaborationNetworkEdge(BaseModel):
|
||||
raw_source_id: str = Field(
|
||||
title="Source Raw ID",
|
||||
description="The raw ID of the source node.",
|
||||
)
|
||||
raw_target_id: str = Field(
|
||||
title="Target Raw ID",
|
||||
description="The raw ID of the target node.",
|
||||
)
|
||||
|
||||
def __eq__(self, value: object) -> bool:
|
||||
if isinstance(value, CollaborationNetworkEdge):
|
||||
return self.same_collaboration(self, value)
|
||||
return False
|
||||
|
||||
def __hash__(self) -> int:
|
||||
return hash((self.raw_source_id, self.raw_target_id))
|
||||
|
||||
@classmethod
|
||||
def same_collaboration(
|
||||
cls, edge1: "CollaborationNetworkEdge", edge2: "CollaborationNetworkEdge"
|
||||
) -> bool:
|
||||
"""Checks if two edges have the same source and target person IDs, regardless of order.
|
||||
|
||||
Args:
|
||||
edge1 (CollaborationNetworkEdge): The first collaboration edge.
|
||||
edge2 (CollaborationNetworkEdge): The second collaboration edge.
|
||||
Returns:
|
||||
bool: True if the edges have the same source and target person IDs (undirected), False otherwise.
|
||||
"""
|
||||
return (
|
||||
edge1.raw_source_id == edge2.raw_source_id
|
||||
and edge1.raw_target_id == edge2.raw_target_id
|
||||
) or (
|
||||
edge1.raw_source_id == edge2.raw_target_id
|
||||
and edge1.raw_target_id == edge2.raw_source_id
|
||||
)
|
||||
|
||||
|
||||
class CollaborationNetwork(BaseModel):
|
||||
raw_person_id: str = Field(
|
||||
title="Raw Person ID",
|
||||
description="The raw person ID of the person whose collaboration network this is.",
|
||||
)
|
||||
work_nodes: List[WorkNetworkNode] = Field(
|
||||
title="Collaboration Network Work Nodes",
|
||||
description="The work nodes in the collaboration network.",
|
||||
)
|
||||
author_nodes: List[AuthorNetworkNode] = Field(
|
||||
title="Collaboration Network Author Nodes",
|
||||
description="The author nodes in the collaboration network.",
|
||||
)
|
||||
institution_nodes: List[InstitutionNetworkNode] = Field(
|
||||
title="Collaboration Network Institution Nodes",
|
||||
description="The institution nodes in the collaboration network.",
|
||||
)
|
||||
collaboration_edges: List[CollaborationNetworkEdge] = Field(
|
||||
title="Collaboration Network Edges",
|
||||
description="The collaboration edges in the collaboration network. A collaboration edge represents a collaboration between two nodes. A -> W and A -> I",
|
||||
)
|
||||
filter_information: FilterInformation = Field(
|
||||
title="Filter Information",
|
||||
description="The filter information for the collaboration network, including the minimum and maximum publication years of the works in the collaboration network.",
|
||||
)
|
||||
@@ -1,708 +0,0 @@
|
||||
from collections import defaultdict
|
||||
import logging
|
||||
from typing import List, Optional, Set, Tuple
|
||||
|
||||
from inse.collaboration_network.schemas import (
|
||||
AuthorNetworkNode,
|
||||
AuthorsFilterProperties,
|
||||
CollaborationNetwork,
|
||||
CollaborationNetworkEdge,
|
||||
CollaborationNetworkNodeType,
|
||||
FilterInformation,
|
||||
FilterProperties,
|
||||
InstitutionInformation,
|
||||
InstitutionNetworkNode,
|
||||
WorkNetworkNode,
|
||||
WorkTopicInformation,
|
||||
WorksFilterProperties,
|
||||
)
|
||||
|
||||
from inse.works import logic as work_logic
|
||||
from inse.works.model import Work
|
||||
|
||||
from inse.utils import (
|
||||
extract_raw_author_id,
|
||||
extract_raw_institution_id,
|
||||
extract_raw_topic_id,
|
||||
extract_raw_work_id,
|
||||
)
|
||||
from inse.models.openalex.author import Author
|
||||
from inse.models.openalex.authorship import Authorship
|
||||
from inse.models.openalex.dehydrated_author import DehydratedAuthor
|
||||
from inse.models.openalex.dehydrated_institution import DehydratedInstitution
|
||||
from inse.models.openalex.institution import Institution
|
||||
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
logger.setLevel(logging.INFO)
|
||||
|
||||
|
||||
async def get_collaboration_network(
|
||||
raw_user_id: str,
|
||||
filter_properties: FilterProperties,
|
||||
) -> CollaborationNetwork:
|
||||
"""Generates a collaboration network for a given user ID based on the works associated with that user, and applies filtering to the network based on the specified filter properties, which may include criteria such as publication year range, allowed topics, minimum/maximum number of contributors, and minimum/maximum number of collaborations.
|
||||
The function returns a collaboration network that includes the works, authors, and institutions that are relevant to the specified user and meet the filtering criteria defined in the filter properties.
|
||||
|
||||
Args:
|
||||
raw_user_id (str): The raw user ID for whom to generate the collaboration network.
|
||||
filter_properties (FilterProperties): The filter properties for the collaboration network.
|
||||
|
||||
Returns:
|
||||
CollaborationNetwork: The collaboration network for the given user.
|
||||
"""
|
||||
|
||||
raw_user_id = raw_user_id.strip().upper()
|
||||
|
||||
work_page = await work_logic.get_all_author_works(author_id=raw_user_id)
|
||||
|
||||
works: List[Work] = work_page.results or []
|
||||
collaboration_network = build_collaboration_network(
|
||||
raw_user_id=raw_user_id, works=works
|
||||
)
|
||||
if filter_properties.filter_by == "works":
|
||||
if not filter_properties.works_filter_properties:
|
||||
filter_properties.works_filter_properties = WorksFilterProperties()
|
||||
return filter_collaboration_network_by_works(
|
||||
raw_user_id=raw_user_id,
|
||||
collaboration_network=collaboration_network,
|
||||
works_filter_properties=filter_properties.works_filter_properties,
|
||||
)
|
||||
elif filter_properties.filter_by == "authors":
|
||||
if not filter_properties.authors_filter_properties:
|
||||
filter_properties.authors_filter_properties = AuthorsFilterProperties()
|
||||
return filter_collaboration_network_by_authors(
|
||||
raw_user_id=raw_user_id,
|
||||
collaboration_network=collaboration_network,
|
||||
filter_properties=filter_properties.authors_filter_properties,
|
||||
)
|
||||
else:
|
||||
logger.warning(
|
||||
f"Invalid filter_by value in filter properties: {filter_properties.filter_by}. Expected 'works' or 'authors'. No additional filtering will be applied."
|
||||
)
|
||||
return collaboration_network
|
||||
|
||||
|
||||
def filter_collaboration_network_by_authors(
|
||||
raw_user_id: str,
|
||||
collaboration_network: CollaborationNetwork,
|
||||
filter_properties: AuthorsFilterProperties,
|
||||
) -> CollaborationNetwork:
|
||||
"""Filters the given collaboration network based on the specified author filter properties, which may include criteria such as allowed institutions and minimum/maximum number of collaborations.
|
||||
The function returns a new collaboration network that only includes authors that meet the specified criteria, along with their associated works and institutions.
|
||||
|
||||
Args:
|
||||
raw_user_id (str): The raw user ID for whom to filter the collaboration network.
|
||||
collaboration_network (CollaborationNetwork): The collaboration network to filter.
|
||||
filter_properties (AuthorsFilterProperties): The filter properties for the author filtering.
|
||||
|
||||
Returns:
|
||||
CollaborationNetwork: The filtered collaboration network.
|
||||
"""
|
||||
logger.debug(
|
||||
f"Filtering collaboration network for user {raw_user_id} with author filter properties: {filter_properties}"
|
||||
)
|
||||
|
||||
all_author_nodes = set(collaboration_network.author_nodes)
|
||||
remaining_author_ids = {node.raw_id for node in all_author_nodes}
|
||||
remaining_institution_nodes = set(collaboration_network.institution_nodes)
|
||||
|
||||
logger.debug(f"Remaining author IDs before filtering: {remaining_author_ids}")
|
||||
# 1. Filter author nodes based on allowed institutions in filter properties
|
||||
if len(filter_properties.allowed_institutions) > 0:
|
||||
logger.debug(
|
||||
f"Filtering author nodes based on allowed institutions: {filter_properties.allowed_institutions}"
|
||||
)
|
||||
remaining_author_ids = {
|
||||
edge.raw_source_id
|
||||
for edge in collaboration_network.collaboration_edges
|
||||
if edge.raw_target_id in filter_properties.allowed_institutions
|
||||
}
|
||||
remaining_institution_nodes = {
|
||||
node
|
||||
for node in collaboration_network.institution_nodes
|
||||
if node.raw_id in filter_properties.allowed_institutions
|
||||
}
|
||||
logger.debug(
|
||||
f"Remaining author IDs after filtering by allowed institutions: {remaining_author_ids}"
|
||||
)
|
||||
|
||||
# 2. Filter out collaboration edges that are associated with author nodes that have been filtered out
|
||||
remaining_work_edges = {
|
||||
edge
|
||||
for edge in collaboration_network.collaboration_edges
|
||||
if edge.raw_source_id in remaining_author_ids
|
||||
and edge.raw_target_id.lower().startswith("w")
|
||||
}
|
||||
logger.debug(
|
||||
f"Remaining work edges after filtering by allowed institutions: {len(remaining_work_edges)}"
|
||||
)
|
||||
|
||||
works_per_author = defaultdict(set)
|
||||
for edge in remaining_work_edges:
|
||||
if (
|
||||
edge.raw_source_id in remaining_author_ids
|
||||
and edge.raw_target_id.lower().startswith("w")
|
||||
):
|
||||
works_per_author[edge.raw_source_id].add(edge.raw_target_id)
|
||||
|
||||
logger.debug(
|
||||
f"Works per author after filtering by allowed institutions: {dict(works_per_author)}"
|
||||
)
|
||||
|
||||
# 3. Filter out author that do not have enough collaborations based on the filter properties
|
||||
remaining_author_ids = {
|
||||
author_id
|
||||
for author_id, work_ids in works_per_author.items()
|
||||
if filter_properties.min_collaborations
|
||||
<= len(work_ids)
|
||||
<= filter_properties.max_collaborations
|
||||
}
|
||||
remaining_author_ids.add(raw_user_id) # main author always included
|
||||
remaining_author_nodes = {
|
||||
node
|
||||
for node in collaboration_network.author_nodes
|
||||
if node.raw_id in remaining_author_ids
|
||||
}
|
||||
|
||||
remaining_institutions_edges = {
|
||||
edge
|
||||
for edge in collaboration_network.collaboration_edges
|
||||
if edge.raw_source_id in remaining_author_ids
|
||||
and edge.raw_target_id.lower().startswith("i")
|
||||
}
|
||||
|
||||
# 4. Remove institution nodes that are not connected to any of the remaining author nodes
|
||||
institution_ids_with_remaining_authors = {
|
||||
edge.raw_target_id
|
||||
for edge in remaining_institutions_edges
|
||||
if edge.raw_source_id in remaining_author_ids
|
||||
}
|
||||
remaining_institution_nodes = {
|
||||
node
|
||||
for node in remaining_institution_nodes
|
||||
if node.raw_id in institution_ids_with_remaining_authors
|
||||
}
|
||||
|
||||
return CollaborationNetwork(
|
||||
raw_person_id=raw_user_id,
|
||||
work_nodes=collaboration_network.work_nodes,
|
||||
author_nodes=list(remaining_author_nodes),
|
||||
institution_nodes=list(remaining_institution_nodes),
|
||||
collaboration_edges=list(remaining_work_edges)
|
||||
+ list(remaining_institutions_edges),
|
||||
filter_information=collaboration_network.filter_information,
|
||||
)
|
||||
|
||||
|
||||
def filter_collaboration_network_by_works(
|
||||
raw_user_id: str,
|
||||
collaboration_network: CollaborationNetwork,
|
||||
works_filter_properties: WorksFilterProperties,
|
||||
) -> CollaborationNetwork:
|
||||
"""Filters the given collaboration network based on the specified works filter properties, which may include criteria such as publication year range, allowed topics, and minimum/maximum number of contributors.
|
||||
The function returns a new collaboration network that only includes works that meet the specified criteria, along with their associated authors and institutions.
|
||||
|
||||
Args:
|
||||
raw_user_id (str): _description_
|
||||
collaboration_network (CollaborationNetwork): _description_
|
||||
works_filter_properties (WorksFilterProperties): _description_
|
||||
|
||||
Returns:
|
||||
CollaborationNetwork: The filtered collaboration network.
|
||||
"""
|
||||
if not works_filter_properties:
|
||||
return collaboration_network
|
||||
|
||||
all_work_nodes = set(collaboration_network.work_nodes)
|
||||
valid_work_ids = {node.raw_id for node in all_work_nodes}
|
||||
|
||||
# 1. Filter out works that are not in the specified year range or do not have allowed topics, and update valid_work_ids accordingly
|
||||
valid_work_ids = filter_works_by_year_and_topic(
|
||||
works=all_work_nodes,
|
||||
filter_properties=works_filter_properties,
|
||||
valid_work_ids=valid_work_ids,
|
||||
)
|
||||
|
||||
# 2. Filter out works that do not have enough collaborators based on the filter properties, and update valid_work_ids accordingly
|
||||
if (
|
||||
works_filter_properties.min_contributors
|
||||
or works_filter_properties.max_contributors
|
||||
):
|
||||
contributors_per_work = defaultdict(set)
|
||||
for edge in collaboration_network.collaboration_edges:
|
||||
if (
|
||||
edge.raw_target_id.lower().startswith("w")
|
||||
and edge.raw_target_id in valid_work_ids
|
||||
):
|
||||
contributors_per_work[edge.raw_target_id].add(edge.raw_source_id)
|
||||
|
||||
valid_work_ids = set()
|
||||
for work_id, contributors in contributors_per_work.items():
|
||||
contributors_count = len(contributors)
|
||||
if has_enough_contributors(
|
||||
contributors_count=contributors_count,
|
||||
filter_properties=works_filter_properties,
|
||||
):
|
||||
valid_work_ids.add(work_id)
|
||||
|
||||
# 3. Filter out collaboration edges that are associated with works that have been filtered out
|
||||
remaining_work_edges = {
|
||||
edge
|
||||
for edge in collaboration_network.collaboration_edges
|
||||
if edge.raw_target_id in valid_work_ids
|
||||
and edge.raw_target_id.lower().startswith("w")
|
||||
}
|
||||
|
||||
# 4. Identify author nodes that are still valid based on their association with the remaining valid works
|
||||
author_ids_with_valid_works = {edge.raw_source_id for edge in remaining_work_edges}
|
||||
|
||||
# 5. Identify institution nodes that are still valid based on their association with the remaining valid author nodes
|
||||
institution_ids_with_valid_authors = {
|
||||
edge.raw_target_id
|
||||
for edge in collaboration_network.collaboration_edges
|
||||
if edge.raw_source_id in author_ids_with_valid_works
|
||||
and edge.raw_target_id.lower().startswith("i")
|
||||
}
|
||||
|
||||
remaining_collaboration_edges = {
|
||||
edge
|
||||
for edge in collaboration_network.collaboration_edges
|
||||
if (
|
||||
edge.raw_target_id in valid_work_ids
|
||||
and edge.raw_target_id.lower().startswith("w")
|
||||
)
|
||||
or (
|
||||
edge.raw_source_id in author_ids_with_valid_works
|
||||
and edge.raw_target_id.lower().startswith("i")
|
||||
)
|
||||
or (
|
||||
edge.raw_source_id in author_ids_with_valid_works
|
||||
and edge.raw_target_id in institution_ids_with_valid_authors
|
||||
)
|
||||
}
|
||||
remaining_work_nodes = {
|
||||
node
|
||||
for node in collaboration_network.work_nodes
|
||||
if node.raw_id in valid_work_ids
|
||||
}
|
||||
remaining_author_nodes = {
|
||||
node
|
||||
for node in collaboration_network.author_nodes
|
||||
if node.raw_id in author_ids_with_valid_works
|
||||
}
|
||||
remaining_institution_nodes = {
|
||||
node
|
||||
for node in collaboration_network.institution_nodes
|
||||
if node.raw_id in institution_ids_with_valid_authors
|
||||
}
|
||||
|
||||
return CollaborationNetwork(
|
||||
raw_person_id=raw_user_id,
|
||||
work_nodes=list(remaining_work_nodes),
|
||||
author_nodes=list(remaining_author_nodes),
|
||||
institution_nodes=list(remaining_institution_nodes),
|
||||
collaboration_edges=list(remaining_collaboration_edges),
|
||||
filter_information=collaboration_network.filter_information,
|
||||
)
|
||||
|
||||
|
||||
def filter_works_by_year_and_topic(
|
||||
works: Set[WorkNetworkNode],
|
||||
filter_properties: WorksFilterProperties,
|
||||
valid_work_ids: Set[str],
|
||||
):
|
||||
"""Determines the set of valid work IDs by filtering the given set of works based on the specified year range and allowed topics defined in the filter properties.
|
||||
|
||||
Args:
|
||||
works (Set[WorkNetworkNode]): The set of works to filter.
|
||||
filter_properties (WorksFilterProperties): The filter properties containing the year range and allowed topics.
|
||||
valid_work_ids (Set[str]): The set of valid work IDs to update.
|
||||
|
||||
Returns:
|
||||
Set[str]: The updated set of valid work IDs.
|
||||
"""
|
||||
if not any(
|
||||
[
|
||||
filter_properties.start_year,
|
||||
filter_properties.end_year,
|
||||
filter_properties.allowed_topics,
|
||||
]
|
||||
):
|
||||
return valid_work_ids
|
||||
|
||||
for work in works:
|
||||
if not is_in_year_range(
|
||||
year=work.publication_year or -1,
|
||||
works_filter_properties=filter_properties,
|
||||
) or not has_allowed_topic(work, filter_properties):
|
||||
valid_work_ids.discard(work.raw_id)
|
||||
|
||||
return valid_work_ids
|
||||
|
||||
|
||||
def is_in_year_range(year: int, works_filter_properties: WorksFilterProperties) -> bool:
|
||||
"""Determines whether a given year falls within the specified year range defined in the filter properties.
|
||||
|
||||
Args:
|
||||
year (int): The year to check.
|
||||
works_filter_properties (WorksFilterProperties): The filter properties containing the year range.
|
||||
|
||||
Returns:
|
||||
bool: True if the year falls within the specified range, False otherwise.
|
||||
"""
|
||||
# no year extracted, excluding work by default
|
||||
if year == -1:
|
||||
return False
|
||||
|
||||
if works_filter_properties.start_year and year < works_filter_properties.start_year:
|
||||
return False
|
||||
|
||||
if works_filter_properties.end_year and year > works_filter_properties.end_year:
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def has_allowed_topic(
|
||||
work: WorkNetworkNode, filter_properties: WorksFilterProperties
|
||||
) -> bool:
|
||||
"""Determines whether a given work has at least one topic that is included in the allowed topics specified in the filter properties.
|
||||
|
||||
Args:
|
||||
work (WorkNetworkNode): The work for which to check the topics.
|
||||
filter_properties (WorksFilterProperties): The filter properties containing the allowed topics.
|
||||
|
||||
Returns:
|
||||
bool: True if the work has at least one allowed topic, False otherwise.
|
||||
"""
|
||||
if len(filter_properties.allowed_topics) == 0:
|
||||
return True
|
||||
return any(
|
||||
topic.raw_topic_id in filter_properties.allowed_topics
|
||||
for topic in work.work_topics_information or set()
|
||||
)
|
||||
|
||||
|
||||
def has_enough_contributors(
|
||||
contributors_count: int, filter_properties: WorksFilterProperties
|
||||
) -> bool:
|
||||
"""Determines whether a given number of contributors meets the specified minimum and maximum contributor requirements defined in the filter properties.
|
||||
|
||||
Args:
|
||||
contributors_count (int): The number of contributors to check.
|
||||
filter_properties (WorksFilterProperties): The filter properties containing the contributor requirements.
|
||||
|
||||
Returns:
|
||||
bool: True if the contributor count meets the requirements, False otherwise.
|
||||
"""
|
||||
if filter_properties and contributors_count < filter_properties.min_contributors:
|
||||
return False
|
||||
if (
|
||||
filter_properties.max_contributors
|
||||
and contributors_count > filter_properties.max_contributors
|
||||
):
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def build_collaboration_network(
|
||||
raw_user_id: str,
|
||||
works: List[Work],
|
||||
) -> CollaborationNetwork:
|
||||
"""Builds a collaboration network for a given user ID based on the provided list of works.
|
||||
|
||||
Args:
|
||||
raw_user_id (str): The raw ID of the user for whom to build the collaboration network.
|
||||
works (List[Work]): The list of works for which to build the collaboration network.
|
||||
|
||||
Returns:
|
||||
CollaborationNetwork: The built collaboration network.
|
||||
"""
|
||||
min_possible_year = float("inf")
|
||||
max_possible_year = float("-inf")
|
||||
|
||||
work_nodes: Set[WorkNetworkNode] = set()
|
||||
all_author_nodes: Set[AuthorNetworkNode] = set()
|
||||
all_institution_nodes: Set[InstitutionNetworkNode] = set()
|
||||
all_collaboration_edges: Set[CollaborationNetworkEdge] = set()
|
||||
|
||||
work_topics_information: Set[WorkTopicInformation] = set()
|
||||
for work in works:
|
||||
work_node, author_nodes, institution_nodes, collaboration_edges = process_work(
|
||||
work=work
|
||||
)
|
||||
if not work_node:
|
||||
continue
|
||||
|
||||
min_possible_year = min(
|
||||
min_possible_year, work_node.publication_year or float("inf")
|
||||
)
|
||||
max_possible_year = max(
|
||||
max_possible_year, work_node.publication_year or float("-inf")
|
||||
)
|
||||
work_topics_information.update(work_node.work_topics_information or set())
|
||||
work_nodes.add(work_node)
|
||||
all_author_nodes.update(author_nodes)
|
||||
all_institution_nodes.update(institution_nodes)
|
||||
all_collaboration_edges.update(collaboration_edges)
|
||||
|
||||
return CollaborationNetwork(
|
||||
raw_person_id=raw_user_id,
|
||||
work_nodes=list(work_nodes),
|
||||
author_nodes=list(all_author_nodes),
|
||||
institution_nodes=list(all_institution_nodes),
|
||||
collaboration_edges=list(all_collaboration_edges),
|
||||
filter_information=FilterInformation(
|
||||
min_possible_year=int(min_possible_year),
|
||||
max_possible_year=int(max_possible_year),
|
||||
institutions=sorted(
|
||||
{
|
||||
InstitutionInformation(
|
||||
raw_id=institution.raw_id, display_name=institution.display_name
|
||||
)
|
||||
for institution in all_institution_nodes
|
||||
},
|
||||
key=lambda inst: inst.display_name,
|
||||
),
|
||||
topics=sorted(
|
||||
work_topics_information, key=lambda topic: topic.display_name
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def process_work(
|
||||
work: Work,
|
||||
) -> Tuple[
|
||||
Optional[WorkNetworkNode],
|
||||
Set[AuthorNetworkNode],
|
||||
Set[InstitutionNetworkNode],
|
||||
Set[CollaborationNetworkEdge],
|
||||
]:
|
||||
"""Processes a given work to extract the associated work node, author nodes, institution nodes, and collaboration edges for the collaboration network.
|
||||
|
||||
Args:
|
||||
work (Work): The work to process.
|
||||
|
||||
Returns:
|
||||
Tuple[ Optional[WorkNetworkNode], Set[AuthorNetworkNode], Set[InstitutionNetworkNode], Set[CollaborationNetworkEdge], ]: A tuple containing the associated work node, author nodes, institution nodes, and collaboration edges.
|
||||
"""
|
||||
year = get_work_year(work)
|
||||
topics_information = extract_topics_information(work=work)
|
||||
|
||||
work_node = create_work_node(
|
||||
work=work, year=year, work_topics_information=topics_information
|
||||
)
|
||||
if not work_node:
|
||||
return None, set(), set(), set()
|
||||
|
||||
authorships = work.authorships
|
||||
if not authorships:
|
||||
return work_node, set(), set(), set()
|
||||
|
||||
author_nodes: Set[AuthorNetworkNode] = set()
|
||||
institution_nodes: Set[InstitutionNetworkNode] = set()
|
||||
collaboration_edges: Set[CollaborationNetworkEdge] = set()
|
||||
|
||||
for authorship in authorships:
|
||||
author_node, institution_nodes, associated_institution_edges = (
|
||||
process_authorship(authorship=authorship)
|
||||
)
|
||||
if not author_node:
|
||||
continue
|
||||
|
||||
work_author_edge = CollaborationNetworkEdge(
|
||||
raw_source_id=author_node.raw_id,
|
||||
raw_target_id=work_node.raw_id,
|
||||
)
|
||||
|
||||
author_nodes.add(author_node)
|
||||
collaboration_edges.add(work_author_edge)
|
||||
institution_nodes.update(institution_nodes)
|
||||
collaboration_edges.update(associated_institution_edges)
|
||||
|
||||
return (
|
||||
work_node,
|
||||
author_nodes,
|
||||
institution_nodes,
|
||||
collaboration_edges,
|
||||
)
|
||||
|
||||
|
||||
def get_work_year(work: Work) -> int:
|
||||
"""Extracts the publication year from a given work.
|
||||
|
||||
Args:
|
||||
work (Work): The work from which to extract the publication year.
|
||||
|
||||
Returns:
|
||||
int: The publication year of the work, or -1 if it cannot be extracted.
|
||||
"""
|
||||
if not work.publication_year:
|
||||
return -1
|
||||
try:
|
||||
return int(work.publication_year)
|
||||
except ValueError:
|
||||
return -1
|
||||
|
||||
|
||||
def create_work_node(
|
||||
work: Work, year: int, work_topics_information: Set[WorkTopicInformation]
|
||||
) -> Optional[WorkNetworkNode]:
|
||||
"""Creates a collaboration network node representing a work based on the provided work data, publication year, and topic information.
|
||||
|
||||
Args:
|
||||
work (Work): The work from which to create the collaboration network node.
|
||||
year (int): The publication year of the work.
|
||||
work_topics_information (Set[WorkTopicInformation]): The topic information of the work.
|
||||
|
||||
Returns:
|
||||
Optional[WorkNetworkNode]: The collaboration network node representing the work, or None if the work data is invalid.
|
||||
"""
|
||||
if not work or not work.id or not work.display_name:
|
||||
return None
|
||||
|
||||
work_id = extract_raw_work_id(work.id)
|
||||
display_name = work.display_name
|
||||
|
||||
return WorkNetworkNode(
|
||||
raw_id=work_id,
|
||||
display_name=display_name,
|
||||
category=CollaborationNetworkNodeType.WORK,
|
||||
publication_year=year,
|
||||
work_topics_information=work_topics_information,
|
||||
)
|
||||
|
||||
|
||||
def extract_topics_information(work: Work) -> Set[WorkTopicInformation]:
|
||||
"""Extracts the topic information from a given work and returns it as a set of WorkTopicInformation objects.
|
||||
|
||||
Args:
|
||||
work (Work): The work from which to extract topic information.
|
||||
|
||||
Returns:
|
||||
Set[WorkTopicInformation]: A set of WorkTopicInformation objects representing the topics of the work.
|
||||
"""
|
||||
topics_information: Set[WorkTopicInformation] = set()
|
||||
for topic in work.topics or []:
|
||||
if not topic.id or not topic.display_name:
|
||||
continue
|
||||
raw_topic_id = extract_raw_topic_id(topic.id)
|
||||
topics_information.add(
|
||||
WorkTopicInformation(
|
||||
raw_topic_id=raw_topic_id, display_name=topic.display_name
|
||||
)
|
||||
)
|
||||
return topics_information
|
||||
|
||||
|
||||
def process_authorship(
|
||||
authorship: Authorship,
|
||||
) -> Tuple[
|
||||
Optional[AuthorNetworkNode],
|
||||
Set[InstitutionNetworkNode],
|
||||
Set[CollaborationNetworkEdge],
|
||||
]:
|
||||
"""Processes a given authorship to extract the associated author node, institution nodes, and collaboration edges.
|
||||
|
||||
Args:
|
||||
authorship (Authorship): The authorship data to process.
|
||||
|
||||
Returns:
|
||||
Tuple[ Optional[AuthorNetworkNode], Set[InstitutionNetworkNode], Set[CollaborationNetworkEdge], ]: A tuple containing the associated author node, institution nodes, and collaboration edges.
|
||||
"""
|
||||
author = authorship.author
|
||||
if not author or not author.id or not author.display_name:
|
||||
return None, set(), set()
|
||||
|
||||
author_node = create_author_node(author)
|
||||
if not author_node:
|
||||
return None, set(), set()
|
||||
|
||||
institution_nodes: Set[InstitutionNetworkNode] = set()
|
||||
for institution in authorship.institutions or []:
|
||||
institution_id = extract_raw_institution_id(institution.id or "")
|
||||
if not institution_id or not institution.display_name:
|
||||
continue
|
||||
|
||||
institution_node = create_institution_node(institution)
|
||||
if institution_node:
|
||||
institution_nodes.add(institution_node)
|
||||
|
||||
associated_institution_edges = create_associated_institution_edges(
|
||||
author_node=author_node, institution_nodes=institution_nodes
|
||||
)
|
||||
|
||||
return author_node, institution_nodes, associated_institution_edges
|
||||
|
||||
|
||||
def create_associated_institution_edges(
|
||||
author_node: AuthorNetworkNode,
|
||||
institution_nodes: Set[InstitutionNetworkNode],
|
||||
) -> Set[CollaborationNetworkEdge]:
|
||||
"""Creates a set of collaboration network edges representing the associations between an author and their affiliated institutions.
|
||||
|
||||
Args:
|
||||
author_node (AuthorNetworkNode): The collaboration network node representing the author.
|
||||
institution_nodes (Set[InstitutionNetworkNode]): A set of collaboration network nodes representing the institutions affiliated with the author.
|
||||
|
||||
Returns:
|
||||
Set[CollaborationNetworkEdge]: A set of collaboration network edges representing the associations between the author and their affiliated institutions.
|
||||
"""
|
||||
return {
|
||||
CollaborationNetworkEdge(
|
||||
raw_source_id=author_node.raw_id,
|
||||
raw_target_id=institution_node.raw_id,
|
||||
)
|
||||
for institution_node in institution_nodes
|
||||
}
|
||||
|
||||
|
||||
def create_author_node(
|
||||
author: Author | DehydratedAuthor,
|
||||
) -> Optional[AuthorNetworkNode]:
|
||||
"""Creates a collaboration network node representing an author based on the provided author data.
|
||||
|
||||
Args:
|
||||
author (Author | DehydratedAuthor): The author data from which to create the collaboration network node.
|
||||
|
||||
Returns:
|
||||
Optional[AuthorNetworkNode]: The collaboration network node representing the author, or None if the author data is invalid.
|
||||
"""
|
||||
if not author or not author.id or not author.display_name:
|
||||
return None
|
||||
|
||||
author_id = extract_raw_author_id(author.id)
|
||||
display_name = author.display_name
|
||||
|
||||
return AuthorNetworkNode(
|
||||
raw_id=author_id,
|
||||
display_name=display_name,
|
||||
category=CollaborationNetworkNodeType.AUTHOR,
|
||||
)
|
||||
|
||||
|
||||
def create_institution_node(
|
||||
institution: Institution | DehydratedInstitution,
|
||||
) -> Optional[InstitutionNetworkNode]:
|
||||
"""Creates a collaboration network node representing an institution based on the provided institution data.
|
||||
|
||||
Args:
|
||||
institution (Institution | DehydratedInstitution): The institution data from which to create the collaboration network node.
|
||||
|
||||
Returns:
|
||||
Optional[InstitutionNetworkNode]: The collaboration network node representing the institution, or None if the institution data is invalid.
|
||||
"""
|
||||
if not institution or not institution.id or not institution.display_name:
|
||||
return None
|
||||
|
||||
institution_id = extract_raw_institution_id(institution.id)
|
||||
display_name = institution.display_name
|
||||
|
||||
return InstitutionNetworkNode(
|
||||
raw_id=institution_id,
|
||||
display_name=display_name,
|
||||
category=CollaborationNetworkNodeType.INSTITUTION,
|
||||
)
|
||||
@@ -69,6 +69,8 @@ class Settings(BaseSettings):
|
||||
elasticsearch_api_key: Optional[str] = None
|
||||
elasticsearch_inse_url: Optional[str] = None
|
||||
elasticsearch_inse_api_key: Optional[str] = None
|
||||
print_es_queries: bool = False
|
||||
print_es_timings: bool = False
|
||||
|
||||
model_config = SettingsConfigDict(env_file=str(ENV_FILE))
|
||||
|
||||
|
||||
@@ -34,6 +34,14 @@ class BmbfProjectStatusStatistics(BaseModel):
|
||||
completed: int
|
||||
|
||||
|
||||
class DfgProjectStatusStatistics(BaseModel):
|
||||
institution_id: str
|
||||
organization_name: str
|
||||
ongoing: int
|
||||
upcoming: int
|
||||
completed: int
|
||||
|
||||
|
||||
class DfgProjectTopic(BaseModel):
|
||||
id: str
|
||||
name: str
|
||||
@@ -60,6 +68,7 @@ class TopAuthor(BaseModel):
|
||||
class TopAuthorStatistics(BaseModel):
|
||||
institution_id: str
|
||||
works: list[TopAuthor]
|
||||
projects: list[TopAuthor]
|
||||
eu_projects: list[TopAuthor]
|
||||
patents: list[TopAuthor]
|
||||
news: list[TopAuthor]
|
||||
|
||||
@@ -12,6 +12,7 @@ from .model import (
|
||||
BmbfProjectStatusStatistics,
|
||||
DashboardStatisticValue,
|
||||
DashboardStatistics,
|
||||
DfgProjectStatusStatistics,
|
||||
DfgProjectTopics,
|
||||
EuProjectStatusStatistics,
|
||||
TopAuthorStatistics,
|
||||
@@ -22,6 +23,7 @@ from .service import (
|
||||
get_dashboard_bmbf_project_statuses,
|
||||
get_dashboard_bmbf_projects,
|
||||
get_dashboard_dfg_projects,
|
||||
get_dashboard_dfg_project_statuses,
|
||||
get_dashboard_dfg_topics,
|
||||
get_dashboard_eu_projects,
|
||||
get_dashboard_eu_project_statuses,
|
||||
@@ -60,6 +62,8 @@ async def dashboard_statistics(
|
||||
response_model=DashboardStatisticValue,
|
||||
)
|
||||
async def dashboard_publications(
|
||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
to_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> DashboardStatisticValue:
|
||||
@@ -67,6 +71,8 @@ async def dashboard_publications(
|
||||
return await get_dashboard_publications(
|
||||
organization.openalex_institution_id,
|
||||
organization.name,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
|
||||
|
||||
@@ -92,6 +98,8 @@ async def dashboard_persons(
|
||||
response_model=DashboardStatisticValue,
|
||||
)
|
||||
async def dashboard_patents(
|
||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
to_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> DashboardStatisticValue:
|
||||
@@ -99,6 +107,8 @@ async def dashboard_patents(
|
||||
return await get_dashboard_patents(
|
||||
organization.openalex_institution_id,
|
||||
organization.name,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
|
||||
|
||||
@@ -108,6 +118,8 @@ async def dashboard_patents(
|
||||
response_model=DashboardStatisticValue,
|
||||
)
|
||||
async def dashboard_eu_projects(
|
||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
to_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> DashboardStatisticValue:
|
||||
@@ -115,6 +127,8 @@ async def dashboard_eu_projects(
|
||||
return await get_dashboard_eu_projects(
|
||||
organization.openalex_institution_id,
|
||||
organization.name,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
|
||||
|
||||
@@ -124,6 +138,8 @@ async def dashboard_eu_projects(
|
||||
response_model=EuProjectStatusStatistics,
|
||||
)
|
||||
async def dashboard_eu_project_statuses(
|
||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
to_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> EuProjectStatusStatistics:
|
||||
@@ -131,6 +147,8 @@ async def dashboard_eu_project_statuses(
|
||||
return await get_dashboard_eu_project_statuses(
|
||||
organization.openalex_institution_id,
|
||||
organization.name,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
|
||||
|
||||
@@ -140,6 +158,8 @@ async def dashboard_eu_project_statuses(
|
||||
response_model=DashboardStatisticValue,
|
||||
)
|
||||
async def dashboard_bmbf_projects(
|
||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
to_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> DashboardStatisticValue:
|
||||
@@ -147,6 +167,8 @@ async def dashboard_bmbf_projects(
|
||||
return await get_dashboard_bmbf_projects(
|
||||
organization.openalex_institution_id,
|
||||
organization.name,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
|
||||
|
||||
@@ -156,6 +178,8 @@ async def dashboard_bmbf_projects(
|
||||
response_model=BmbfProjectStatusStatistics,
|
||||
)
|
||||
async def dashboard_bmbf_project_statuses(
|
||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
to_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> BmbfProjectStatusStatistics:
|
||||
@@ -163,6 +187,8 @@ async def dashboard_bmbf_project_statuses(
|
||||
return await get_dashboard_bmbf_project_statuses(
|
||||
organization.openalex_institution_id,
|
||||
organization.name,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
|
||||
|
||||
@@ -172,6 +198,8 @@ async def dashboard_bmbf_project_statuses(
|
||||
response_model=DashboardStatisticValue,
|
||||
)
|
||||
async def dashboard_dfg_projects(
|
||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
to_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> DashboardStatisticValue:
|
||||
@@ -179,6 +207,28 @@ async def dashboard_dfg_projects(
|
||||
return await get_dashboard_dfg_projects(
|
||||
organization.openalex_institution_id,
|
||||
organization.name,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/projects/dfg/status",
|
||||
operation_id="getDashboardDfgProjectStatuses",
|
||||
response_model=DfgProjectStatusStatistics,
|
||||
)
|
||||
async def dashboard_dfg_project_statuses(
|
||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
to_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> DfgProjectStatusStatistics:
|
||||
organization = get_dashboard_organization(session, access_token)
|
||||
return await get_dashboard_dfg_project_statuses(
|
||||
organization.openalex_institution_id,
|
||||
organization.name,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
|
||||
|
||||
@@ -188,6 +238,8 @@ async def dashboard_dfg_projects(
|
||||
response_model=DfgProjectTopics,
|
||||
)
|
||||
async def dashboard_dfg_project_topics(
|
||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
to_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> DfgProjectTopics:
|
||||
@@ -195,6 +247,8 @@ async def dashboard_dfg_project_topics(
|
||||
return await get_dashboard_dfg_topics(
|
||||
organization.openalex_institution_id,
|
||||
organization.name,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
|
||||
|
||||
@@ -208,6 +262,8 @@ async def dashboard_top_authors(
|
||||
default="all_time",
|
||||
pattern="^(all_time|last_5_years)$",
|
||||
),
|
||||
from_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
to_year: int | None = Query(default=None, ge=1900, le=2100),
|
||||
session: Session = Depends(get_session),
|
||||
access_token: AccessToken = auth_service.CurrentUserAccessTokenPayloadDep,
|
||||
) -> TopAuthorStatistics:
|
||||
@@ -216,6 +272,8 @@ async def dashboard_top_authors(
|
||||
organization.openalex_institution_id,
|
||||
organization.name,
|
||||
works_period=works_period,
|
||||
from_year=from_year,
|
||||
to_year=to_year,
|
||||
)
|
||||
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,5 +1,6 @@
|
||||
from unittest.mock import AsyncMock, patch
|
||||
from datetime import datetime
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
from fastapi import HTTPException
|
||||
@@ -8,11 +9,8 @@ from sqlmodel import Session, SQLModel, create_engine
|
||||
from inse import config
|
||||
from inse.auth.model import AccessToken, Organization, UserRole
|
||||
from inse.dashboard.service import (
|
||||
get_dashboard_bmbf_project_statuses,
|
||||
_openalex_work_authors_by_eu_projects,
|
||||
get_dashboard_organization,
|
||||
get_dashboard_dfg_topics,
|
||||
get_dashboard_eu_project_statuses,
|
||||
get_dashboard_patents,
|
||||
get_dashboard_statistics,
|
||||
get_top_authors,
|
||||
get_topic_heatmap,
|
||||
@@ -29,137 +27,23 @@ def anyio_backend():
|
||||
return "asyncio"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_dashboard_patents_uses_org_patent_total():
|
||||
with patch(
|
||||
"inse.dashboard.service.OrgPatentsSearchClient.search_by_institution",
|
||||
new=AsyncMock(return_value=([], 42)),
|
||||
) as search:
|
||||
result = await get_dashboard_patents(ORG_INSTITUTION_ID, "Example Org")
|
||||
|
||||
assert result.model_dump() == {
|
||||
"institution_id": ORG_INSTITUTION_ID,
|
||||
"organization_name": "Example Org",
|
||||
"value": 42,
|
||||
}
|
||||
search.assert_awaited_once_with(ORG_INSTITUTION_ID, page=0, size=0)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_dashboard_eu_project_statuses_deduplicates_projects():
|
||||
async def scan(**kwargs):
|
||||
assert kwargs["index"] == str(ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD)
|
||||
assert kwargs["source"] == ["projectID"]
|
||||
yield {"_source": {"projectID": "P2"}}
|
||||
yield {"_source": {"projectID": "P1"}}
|
||||
yield {"_source": {"projectID": "P1"}}
|
||||
|
||||
response = {
|
||||
"aggregations": {
|
||||
"ongoing": {"projects": {"value": 2}},
|
||||
"upcoming": {"projects": {"value": 1}},
|
||||
"completed": {"projects": {"value": 7}},
|
||||
}
|
||||
}
|
||||
with patch(
|
||||
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
|
||||
new=AsyncMock(return_value=["Example University"]),
|
||||
), patch("inse.dashboard.service.elasticsearch.scan", new=scan), patch(
|
||||
"inse.dashboard.service.elasticsearch.search",
|
||||
new=AsyncMock(return_value=response),
|
||||
) as search:
|
||||
result = await get_dashboard_eu_project_statuses(
|
||||
ORG_INSTITUTION_ID,
|
||||
"Example Org",
|
||||
)
|
||||
|
||||
assert result.model_dump() == {
|
||||
"institution_id": ORG_INSTITUTION_ID,
|
||||
"organization_name": "Example Org",
|
||||
"ongoing": 2,
|
||||
"upcoming": 1,
|
||||
"completed": 7,
|
||||
}
|
||||
call = search.await_args
|
||||
assert call.kwargs["index"] == ESIndex.CORDIS_EU_PROJECTS_WILDCARD
|
||||
assert call.kwargs["body"]["query"] == {
|
||||
"terms": {"id": ["P1", "P2"]}
|
||||
}
|
||||
today = datetime.now().date().isoformat()
|
||||
aggregations = call.kwargs["body"]["aggs"]
|
||||
assert aggregations["ongoing"]["filter"]["bool"]["filter"] == [
|
||||
{"range": {"startDate": {"lte": today}}},
|
||||
{"range": {"endDate": {"gte": today}}},
|
||||
]
|
||||
assert aggregations["upcoming"]["filter"] == {
|
||||
"range": {"startDate": {"gt": today}}
|
||||
}
|
||||
assert aggregations["completed"]["filter"] == {
|
||||
"range": {"endDate": {"lt": today}}
|
||||
}
|
||||
assert all(
|
||||
aggregation["aggs"]["projects"]["cardinality"]["field"] == "id"
|
||||
for aggregation in aggregations.values()
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_dashboard_bmbf_project_statuses_uses_funding_dates():
|
||||
response = {
|
||||
"aggregations": {
|
||||
"ongoing": {"doc_count": 4},
|
||||
"upcoming": {"doc_count": 2},
|
||||
"completed": {"doc_count": 19},
|
||||
}
|
||||
}
|
||||
with patch(
|
||||
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
|
||||
new=AsyncMock(return_value=["Example University"]),
|
||||
), patch(
|
||||
"inse.dashboard.service.elasticsearch.search",
|
||||
new=AsyncMock(return_value=response),
|
||||
) as search:
|
||||
result = await get_dashboard_bmbf_project_statuses(
|
||||
ORG_INSTITUTION_ID,
|
||||
"Example Org",
|
||||
)
|
||||
|
||||
assert result.model_dump() == {
|
||||
"institution_id": ORG_INSTITUTION_ID,
|
||||
"organization_name": "Example Org",
|
||||
"ongoing": 4,
|
||||
"upcoming": 2,
|
||||
"completed": 19,
|
||||
}
|
||||
call = search.await_args
|
||||
assert call.kwargs["index"] == ESIndex.PROJECTS_BUND_V1
|
||||
assert call.kwargs["body"]["query"]["bool"]["minimum_should_match"] == 1
|
||||
today = datetime.now().strftime("%d.%m.%Y")
|
||||
aggregations = call.kwargs["body"]["aggs"]
|
||||
assert aggregations["ongoing"]["filter"]["bool"]["filter"] == [
|
||||
{"range": {"funding_start": {"lte": today}}},
|
||||
{"range": {"funding_end": {"gte": today}}},
|
||||
]
|
||||
assert aggregations["upcoming"]["filter"] == {
|
||||
"range": {"funding_start": {"gt": today}}
|
||||
}
|
||||
assert aggregations["completed"]["filter"] == {
|
||||
"range": {"funding_end": {"lt": today}}
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_dashboard_statistics_counts_organization_data_and_all_projects():
|
||||
async def search(**kwargs):
|
||||
index = kwargs["index"]
|
||||
|
||||
if index == config.settings.openalex_works_search_index:
|
||||
return {"hits": {"total": {"value": 120}}}
|
||||
|
||||
if index == ESIndex.OPENALEX_AUTHORS:
|
||||
return {"hits": {"total": {"value": 35}}}
|
||||
|
||||
if index == ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD:
|
||||
return {"aggregations": {"projects": {"value": 10}}}
|
||||
|
||||
if index == ESIndex.PROJECTS_BUND_V1:
|
||||
return {"hits": {"total": {"value": 5}}}
|
||||
|
||||
if index == ESIndex.DFG_INSTITUTES_V2:
|
||||
if "institute_ids" in kwargs["body"].get("aggs", {}):
|
||||
return {
|
||||
@@ -182,6 +66,7 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects():
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {"hits": {"total": {"value": 3}}}
|
||||
|
||||
with patch(
|
||||
@@ -200,7 +85,10 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects():
|
||||
)
|
||||
),
|
||||
):
|
||||
result = await get_dashboard_statistics(ORG_INSTITUTION_ID, "Example Org")
|
||||
result = await get_dashboard_statistics(
|
||||
ORG_INSTITUTION_ID,
|
||||
"Example Org",
|
||||
)
|
||||
|
||||
assert result.model_dump() == {
|
||||
"institution_id": ORG_INSTITUTION_ID,
|
||||
@@ -212,34 +100,34 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects():
|
||||
"eu_projects": 10,
|
||||
"bmbf_projects": 5,
|
||||
}
|
||||
calls = mocked_search.await_args_list
|
||||
calls_by_index = {
|
||||
call.kwargs["index"]: call
|
||||
for call in calls
|
||||
if call.kwargs["index"] != ESIndex.DFG_INSTITUTES_V2
|
||||
}
|
||||
works_call = calls_by_index[config.settings.openalex_works_search_index]
|
||||
authors_call = calls_by_index[ESIndex.OPENALEX_AUTHORS]
|
||||
eu_call = calls_by_index[ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD]
|
||||
bmbf_call = calls_by_index[ESIndex.PROJECTS_BUND_V1]
|
||||
dfg_calls = [
|
||||
|
||||
publication_call = next(
|
||||
call
|
||||
for call in calls
|
||||
if call.kwargs["index"] == ESIndex.DFG_INSTITUTES_V2
|
||||
]
|
||||
dfg_institutes_call, dfg_projects_call = dfg_calls
|
||||
assert works_call.kwargs["query"]["nested"]["query"]["term"] == {
|
||||
for call in mocked_search.await_args_list
|
||||
if call.kwargs["index"] == config.settings.openalex_works_search_index
|
||||
)
|
||||
assert publication_call.kwargs["query"]["nested"]["query"]["term"] == {
|
||||
"authorships.institutions.id": ORG_INSTITUTION_ID
|
||||
}
|
||||
assert authors_call.kwargs["query"]["bool"]["should"][0]["bool"]["filter"][
|
||||
0
|
||||
]["nested"]["query"]["match_phrase"] == {
|
||||
"last_known_institutions.id": ORG_INSTITUTION_ID
|
||||
}
|
||||
assert all(
|
||||
call.kwargs["cluster"] == ESCluster.INSE
|
||||
for call in [eu_call, bmbf_call, *dfg_calls]
|
||||
|
||||
person_call = next(
|
||||
call
|
||||
for call in mocked_search.await_args_list
|
||||
if call.kwargs["index"] == ESIndex.OPENALEX_AUTHORS
|
||||
)
|
||||
person_query = person_call.kwargs["query"]
|
||||
recent_affiliation = person_query["bool"]["should"][0]["bool"]["filter"][1]
|
||||
|
||||
assert recent_affiliation["nested"]["path"] == "affiliations"
|
||||
assert recent_affiliation["nested"]["query"]["bool"]["filter"][0] == {
|
||||
"term": {"affiliations.institution.id": ORG_INSTITUTION_ID}
|
||||
}
|
||||
eu_call = next(
|
||||
call
|
||||
for call in mocked_search.await_args_list
|
||||
if call.kwargs["index"] == ESIndex.CORDIS_EU_ORGANIZATIONS_WILDCARD
|
||||
)
|
||||
assert eu_call.kwargs["cluster"] == ESCluster.INSE
|
||||
assert eu_call.kwargs["body"]["query"] == {
|
||||
"terms": {
|
||||
"name.keyword": [
|
||||
@@ -249,141 +137,32 @@ async def test_dashboard_statistics_counts_organization_data_and_all_projects():
|
||||
]
|
||||
}
|
||||
}
|
||||
assert bmbf_call.kwargs["query"]["bool"]["minimum_should_match"] == 1
|
||||
assert bmbf_call.kwargs["query"]["bool"]["should"][0]["match"] == {
|
||||
|
||||
bund_call = next(
|
||||
call
|
||||
for call in mocked_search.await_args_list
|
||||
if call.kwargs["index"] == ESIndex.PROJECTS_BUND_V1
|
||||
)
|
||||
assert bund_call.kwargs["cluster"] == ESCluster.INSE
|
||||
assert bund_call.kwargs["query"]["bool"]["minimum_should_match"] == 1
|
||||
assert bund_call.kwargs["query"]["bool"]["should"][0]["match"] == {
|
||||
"Zuwendungsempfänger": {
|
||||
"query": "Example Org",
|
||||
"operator": "and",
|
||||
}
|
||||
}
|
||||
dfg_query = dfg_institutes_call.kwargs["body"]["query"]
|
||||
assert dfg_query["bool"]["minimum_should_match"] == 1
|
||||
assert dfg_query["bool"]["should"] == [
|
||||
{
|
||||
"terms": {
|
||||
"institute_name_de.keyword": [
|
||||
"Example University",
|
||||
"Example Universität",
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"terms": {
|
||||
"institute_name_en.keyword": [
|
||||
"Example University",
|
||||
"Example Universität",
|
||||
]
|
||||
}
|
||||
},
|
||||
|
||||
dfg_calls = [
|
||||
call
|
||||
for call in mocked_search.await_args_list
|
||||
if call.kwargs["index"] == ESIndex.DFG_INSTITUTES_V2
|
||||
]
|
||||
assert dfg_projects_call.kwargs["body"]["query"] == {
|
||||
"terms": {"institute_id": [10210]}
|
||||
}
|
||||
assert dfg_projects_call.kwargs["body"]["aggs"] == {
|
||||
"projects_nested": {
|
||||
"nested": {"path": "projects"},
|
||||
"aggs": {
|
||||
"project_ids": {
|
||||
"filter": {
|
||||
"terms": {"projects.institute_ref_id": [10210]}
|
||||
},
|
||||
"aggs": {
|
||||
"values": {
|
||||
"terms": {
|
||||
"field": "projects.project_id",
|
||||
"size": 10000,
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
assert len(dfg_calls) == 2
|
||||
assert all(call.kwargs["cluster"] == ESCluster.INSE for call in dfg_calls)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_dashboard_dfg_topics_returns_deduplicated_topics():
|
||||
async def scan(**kwargs):
|
||||
assert kwargs == {
|
||||
"index": "projects_dfg_openalex_topics",
|
||||
"query": {"terms": {"project_id": ["101", "102"]}},
|
||||
"source": ["project_id", "topic_matches"],
|
||||
"page_size": 1000,
|
||||
"cluster": ESCluster.INSE,
|
||||
}
|
||||
yield {
|
||||
"_source": {
|
||||
"project_id": "101",
|
||||
"topic_matches": [
|
||||
{
|
||||
"topic_id": "https://openalex.org/T1",
|
||||
"topic_display_name": "Topic One",
|
||||
"subfield": "Subfield One",
|
||||
"field": "Field One",
|
||||
"domain": "Domain One",
|
||||
}
|
||||
],
|
||||
}
|
||||
}
|
||||
yield {
|
||||
"_source": {
|
||||
"project_id": "102",
|
||||
"topic_matches": [
|
||||
{
|
||||
"topic_id": "https://openalex.org/T1",
|
||||
"topic_display_name": "Topic One",
|
||||
"subfield": "Subfield One",
|
||||
"field": "Field One",
|
||||
"domain": "Domain One",
|
||||
},
|
||||
{
|
||||
"topic_id": "https://openalex.org/T2",
|
||||
"topic_display_name": "Topic Two",
|
||||
"subfield": "Subfield Two",
|
||||
"field": "Field Two",
|
||||
"domain": "Domain Two",
|
||||
},
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service._get_dfg_project_ids_for_institution",
|
||||
new=AsyncMock(return_value=["101", "102"]),
|
||||
), patch("inse.dashboard.service.elasticsearch.scan", new=scan):
|
||||
result = await get_dashboard_dfg_topics(
|
||||
ORG_INSTITUTION_ID,
|
||||
"Example Org",
|
||||
)
|
||||
|
||||
assert result.model_dump() == {
|
||||
"institution_id": ORG_INSTITUTION_ID,
|
||||
"organization_name": "Example Org",
|
||||
"project_count": 2,
|
||||
"matched_project_count": 2,
|
||||
"topics": [
|
||||
{
|
||||
"id": "https://openalex.org/T1",
|
||||
"name": "Topic One",
|
||||
"subfield": "Subfield One",
|
||||
"field": "Field One",
|
||||
"domain": "Domain One",
|
||||
"project_count": 2,
|
||||
},
|
||||
{
|
||||
"id": "https://openalex.org/T2",
|
||||
"name": "Topic Two",
|
||||
"subfield": "Subfield Two",
|
||||
"field": "Field Two",
|
||||
"domain": "Domain Two",
|
||||
"project_count": 1,
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_top_authors_maps_works_patents_and_news_without_project_queries():
|
||||
async def test_top_authors_maps_works_patents_news_and_eu_projects():
|
||||
async def search(**kwargs):
|
||||
if kwargs["index"] == ESIndex.OPENALEX_AUTHORS:
|
||||
return {
|
||||
@@ -408,31 +187,109 @@ async def test_top_authors_maps_works_patents_and_news_without_project_queries()
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
if kwargs["index"] == "aktuell_postproc":
|
||||
return {
|
||||
"aggregations": {
|
||||
"authors": {
|
||||
"buckets": [{"key": "Ada Example", "doc_count": 6}]
|
||||
}
|
||||
}
|
||||
}
|
||||
if kwargs["index"] == ESIndex.CORDIS_EU_FP7_PUBLICATIONS:
|
||||
return {
|
||||
"aggregations": {
|
||||
"authors": {
|
||||
"buckets": [
|
||||
{"key": "Grace Example", "doc_count": 8},
|
||||
{"key": "Ada Example", "doc_count": 5},
|
||||
{"key": "Ada Example", "doc_count": 6}
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
if kwargs["index"] == ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD:
|
||||
return {
|
||||
"hits": {
|
||||
"hits": [
|
||||
{
|
||||
"_source": {
|
||||
"projectID": "P1",
|
||||
"qaProcessedDoi": "10.1234/p1",
|
||||
}
|
||||
},
|
||||
{
|
||||
"_source": {
|
||||
"projectID": "P2",
|
||||
"qaProcessedDoi": "https://doi.org/10.1234/p2",
|
||||
}
|
||||
},
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
if kwargs["index"] == ESIndex.DFG_PROJECTS:
|
||||
return {
|
||||
"aggregations": {
|
||||
"people": {
|
||||
"buckets": [{"key": "Grace Example", "doc_count": 3}]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if kwargs["index"] == "openalex-works":
|
||||
return {
|
||||
"hits": {
|
||||
"hits": [
|
||||
{
|
||||
"_source": {
|
||||
"doi": "https://doi.org/10.1234/p1",
|
||||
"authorships": [
|
||||
{
|
||||
"author": {
|
||||
"id": "https://openalex.org/A2",
|
||||
"display_name": "Grace Example",
|
||||
},
|
||||
"institutions": [{"id": ORG_INSTITUTION_ID}],
|
||||
},
|
||||
{
|
||||
"author": {
|
||||
"id": "https://openalex.org/A1",
|
||||
"display_name": "Ada Example",
|
||||
},
|
||||
"institutions": [{"id": ORG_INSTITUTION_ID}],
|
||||
},
|
||||
],
|
||||
}
|
||||
},
|
||||
{
|
||||
"_source": {
|
||||
"doi": "https://doi.org/10.1234/p2",
|
||||
"authorships": [
|
||||
{
|
||||
"author": {
|
||||
"id": "https://openalex.org/A2",
|
||||
"display_name": "Grace Example",
|
||||
},
|
||||
"institutions": [{"id": ORG_INSTITUTION_ID}],
|
||||
}
|
||||
],
|
||||
}
|
||||
},
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
return {"aggregations": {"people": {"buckets": []}}}
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.elasticsearch.search",
|
||||
new=AsyncMock(side_effect=search),
|
||||
) as mocked_search, patch(
|
||||
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
|
||||
new=AsyncMock(return_value=["Example University"]),
|
||||
), patch(
|
||||
"inse.dashboard.service.get_eu_organization_project_contributions",
|
||||
new=AsyncMock(
|
||||
return_value=SimpleNamespace(
|
||||
elements=[
|
||||
SimpleNamespace(project_id="P1"),
|
||||
SimpleNamespace(project_id="P2"),
|
||||
SimpleNamespace(project_id="P3"),
|
||||
],
|
||||
)
|
||||
),
|
||||
), patch(
|
||||
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
|
||||
new=AsyncMock(
|
||||
return_value=[
|
||||
@@ -440,7 +297,10 @@ async def test_top_authors_maps_works_patents_and_news_without_project_queries()
|
||||
]
|
||||
),
|
||||
):
|
||||
result = await get_top_authors(ORG_INSTITUTION_ID, "Example Org")
|
||||
result = await get_top_authors(
|
||||
ORG_INSTITUTION_ID,
|
||||
"Example Org",
|
||||
)
|
||||
|
||||
assert result.works[0].model_dump() == {
|
||||
"id": "A1",
|
||||
@@ -453,30 +313,295 @@ async def test_top_authors_maps_works_patents_and_news_without_project_queries()
|
||||
"count": 4,
|
||||
}
|
||||
assert [author.model_dump() for author in result.eu_projects] == [
|
||||
{"id": None, "name": "Grace Example", "count": 8},
|
||||
{"id": None, "name": "Ada Example", "count": 5},
|
||||
{"id": "A2", "name": "Grace Example", "count": 2},
|
||||
{"id": "A1", "name": "Ada Example", "count": 1},
|
||||
]
|
||||
assert result.news[0].model_dump() == {
|
||||
"id": "A1",
|
||||
"name": "Ada Example",
|
||||
"count": 6,
|
||||
}
|
||||
|
||||
project_calls = [
|
||||
call
|
||||
for call in mocked_search.await_args_list
|
||||
if call.kwargs["index"]
|
||||
in {ESIndex.DFG_PROJECTS_V2, ESIndex.PROJECTS_BUND_V1}
|
||||
in {ESIndex.DFG_PROJECTS, ESIndex.PROJECTS_BUND_V1}
|
||||
]
|
||||
assert project_calls == []
|
||||
|
||||
eu_calls = [
|
||||
call
|
||||
for call in mocked_search.await_args_list
|
||||
if call.kwargs["index"] == ESIndex.CORDIS_EU_FP7_PUBLICATIONS
|
||||
if call.kwargs["index"] == ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD
|
||||
]
|
||||
assert len(eu_calls) == 1
|
||||
terms = eu_calls[0].kwargs["body"]["aggs"]["authors"]["terms"]
|
||||
assert terms["size"] == 10
|
||||
assert "splitOnToken(';')" in terms["script"]["source"]
|
||||
|
||||
eu_body = eu_calls[0].kwargs["body"]
|
||||
assert set(eu_body["query"]["terms"]["projectID"]) == {
|
||||
"P1",
|
||||
"P2",
|
||||
"P3",
|
||||
}
|
||||
assert eu_body["_source"] == ["projectID", "qaProcessedDoi"]
|
||||
assert "aggs" not in eu_body
|
||||
|
||||
works_calls = [
|
||||
call
|
||||
for call in mocked_search.await_args_list
|
||||
if call.kwargs["index"] == "openalex-works"
|
||||
]
|
||||
assert len(works_calls) == 1
|
||||
works_body = works_calls[0].kwargs["body"]
|
||||
assert works_body["query"]["bool"]["filter"][0]["terms"]["doi"] == [
|
||||
"https://doi.org/10.1234/p1",
|
||||
"https://doi.org/10.1234/p2",
|
||||
]
|
||||
assert works_body["_source"] == [
|
||||
"doi",
|
||||
"authorships.author.id",
|
||||
"authorships.author.display_name",
|
||||
"authorships.institutions.id",
|
||||
]
|
||||
|
||||
|
||||
def test_eu_author_count_groups_multiple_publications_by_project_id():
|
||||
works_response = {
|
||||
"hits": {
|
||||
"hits": [
|
||||
{
|
||||
"_source": {
|
||||
"doi": "https://doi.org/10.1/marcus-a",
|
||||
"authorships": [
|
||||
{
|
||||
"author": {
|
||||
"id": "https://openalex.org/A5007170803",
|
||||
"display_name": "Marcus Example",
|
||||
},
|
||||
"institutions": [{"id": ORG_INSTITUTION_ID}],
|
||||
},
|
||||
{
|
||||
"author": {
|
||||
"id": "https://openalex.org/A999",
|
||||
"display_name": "External Example",
|
||||
},
|
||||
"institutions": [{"id": ORG_INSTITUTION_ID}],
|
||||
},
|
||||
],
|
||||
}
|
||||
},
|
||||
{
|
||||
"_source": {
|
||||
"doi": "https://doi.org/10.1/marcus-b",
|
||||
"authorships": [
|
||||
{
|
||||
"author": {
|
||||
"id": "https://openalex.org/A5007170803",
|
||||
"display_name": "Marcus Example",
|
||||
},
|
||||
"institutions": [{"id": ORG_INSTITUTION_ID}],
|
||||
}
|
||||
],
|
||||
}
|
||||
},
|
||||
]
|
||||
}
|
||||
}
|
||||
doi_project_ids = {
|
||||
"https://doi.org/10.1/marcus-a": {"P1"},
|
||||
"https://doi.org/10.1/marcus-b": {"P1"},
|
||||
}
|
||||
|
||||
result = _openalex_work_authors_by_eu_projects(
|
||||
works_response,
|
||||
doi_project_ids,
|
||||
ORG_INSTITUTION_ID,
|
||||
{"https://openalex.org/A5007170803"},
|
||||
)
|
||||
|
||||
assert [author.model_dump() for author in result] == [
|
||||
{"id": "A5007170803", "name": "Marcus Example", "count": 1}
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_top_eu_project_authors_count_filtered_projects_by_stable_author_id():
|
||||
async def search(**kwargs):
|
||||
if kwargs["index"] == ESIndex.OPENALEX_AUTHORS:
|
||||
return {
|
||||
"hits": {
|
||||
"hits": [
|
||||
{
|
||||
"_source": {
|
||||
"id": "https://openalex.org/A1",
|
||||
"display_name": "Ada Example",
|
||||
"works_count": 3,
|
||||
"counts_by_year": [],
|
||||
}
|
||||
},
|
||||
{
|
||||
"_source": {
|
||||
"id": "https://openalex.org/A2",
|
||||
"display_name": "Grace Example",
|
||||
"works_count": 1,
|
||||
"counts_by_year": [],
|
||||
}
|
||||
},
|
||||
]
|
||||
}
|
||||
}
|
||||
if kwargs["index"] == ESIndex.CORDIS_EU_PUBLICATIONS_WILDCARD:
|
||||
assert kwargs["body"]["query"] == {
|
||||
"terms": {"projectID": ["P1", "P2"]}
|
||||
}
|
||||
return {
|
||||
"hits": {
|
||||
"hits": [
|
||||
{
|
||||
"_source": {
|
||||
"projectID": "P1",
|
||||
"qaProcessedDoi": "10.1/P1-A",
|
||||
}
|
||||
},
|
||||
{
|
||||
"_source": {
|
||||
"projectID": "P1",
|
||||
"qaProcessedDoi": "10.1/P1-B",
|
||||
}
|
||||
},
|
||||
{
|
||||
"_source": {
|
||||
"projectID": "P2",
|
||||
"qaProcessedDoi": "10.1/P2",
|
||||
}
|
||||
},
|
||||
{
|
||||
"_source": {
|
||||
"projectID": "OUTSIDE",
|
||||
"qaProcessedDoi": "10.1/OUT",
|
||||
}
|
||||
},
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
if kwargs["index"] == "openalex-works":
|
||||
assert kwargs["body"]["query"]["bool"]["filter"][0]["terms"]["doi"] == [
|
||||
"https://doi.org/10.1/p1-a",
|
||||
"https://doi.org/10.1/p1-b",
|
||||
"https://doi.org/10.1/p2",
|
||||
]
|
||||
return {
|
||||
"hits": {
|
||||
"hits": [
|
||||
{
|
||||
"_source": {
|
||||
"doi": "https://doi.org/10.1/p1-a",
|
||||
"authorships": [
|
||||
{
|
||||
"author": {
|
||||
"id": "https://openalex.org/A1",
|
||||
"display_name": "Ada Example",
|
||||
},
|
||||
"institutions": [{"id": ORG_INSTITUTION_ID}],
|
||||
},
|
||||
{
|
||||
"author": {
|
||||
"id": "https://openalex.org/A2",
|
||||
"display_name": "Grace Example",
|
||||
},
|
||||
"institutions": [{"id": ORG_INSTITUTION_ID}],
|
||||
},
|
||||
],
|
||||
}
|
||||
},
|
||||
{
|
||||
"_source": {
|
||||
"doi": "https://doi.org/10.1/p1-b",
|
||||
"authorships": [
|
||||
{
|
||||
"author": {
|
||||
"id": "https://openalex.org/A1",
|
||||
"display_name": "Ada Example",
|
||||
},
|
||||
"institutions": [{"id": ORG_INSTITUTION_ID}],
|
||||
}
|
||||
],
|
||||
}
|
||||
},
|
||||
{
|
||||
"_source": {
|
||||
"doi": "https://doi.org/10.1/p2",
|
||||
"authorships": [
|
||||
{
|
||||
"author": {
|
||||
"id": "https://openalex.org/A1",
|
||||
"display_name": "Ada Example",
|
||||
},
|
||||
"institutions": [{"id": ORG_INSTITUTION_ID}],
|
||||
}
|
||||
],
|
||||
}
|
||||
},
|
||||
{
|
||||
"_source": {
|
||||
"doi": "https://doi.org/10.1/not-requested",
|
||||
"authorships": [
|
||||
{
|
||||
"author": {
|
||||
"id": "https://openalex.org/A999",
|
||||
"display_name": "Outside Author",
|
||||
}
|
||||
}
|
||||
],
|
||||
}
|
||||
},
|
||||
]
|
||||
}
|
||||
}
|
||||
if kwargs["index"] == ESIndex.DFG_PROJECTS:
|
||||
return {
|
||||
"aggregations": {
|
||||
"people": {
|
||||
"buckets": [
|
||||
{"key": "Ada Example", "doc_count": 2},
|
||||
{"key": "ada example", "doc_count": 3},
|
||||
{"key": "DFG Person", "doc_count": 4},
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
return {"aggregations": {"authors": {"buckets": []}}}
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.elasticsearch.search",
|
||||
new=AsyncMock(side_effect=search),
|
||||
), patch(
|
||||
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
|
||||
new=AsyncMock(return_value=["Example University"]),
|
||||
), patch(
|
||||
"inse.dashboard.service.get_eu_organization_project_contributions",
|
||||
new=AsyncMock(
|
||||
return_value=SimpleNamespace(
|
||||
elements=[
|
||||
SimpleNamespace(project_id="P1"),
|
||||
SimpleNamespace(project_id="P2"),
|
||||
],
|
||||
)
|
||||
),
|
||||
), patch(
|
||||
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
|
||||
new=AsyncMock(return_value=[]),
|
||||
):
|
||||
result = await get_top_authors(
|
||||
ORG_INSTITUTION_ID,
|
||||
"Example Org",
|
||||
)
|
||||
|
||||
assert [author.model_dump() for author in result.eu_projects] == [
|
||||
{"id": "A1", "name": "Ada Example", "count": 2},
|
||||
{"id": "A2", "name": "Grace Example", "count": 1},
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
@@ -497,16 +622,32 @@ async def test_top_authors_returns_partial_response_when_one_source_fails():
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
raise RuntimeError("projects unavailable")
|
||||
|
||||
with patch(
|
||||
"inse.dashboard.service.elasticsearch.search",
|
||||
new=AsyncMock(side_effect=search),
|
||||
), patch(
|
||||
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
|
||||
new=AsyncMock(return_value=["Example University"]),
|
||||
), patch(
|
||||
"inse.dashboard.service.get_eu_organization_project_contributions",
|
||||
new=AsyncMock(
|
||||
return_value=SimpleNamespace(
|
||||
elements=[
|
||||
SimpleNamespace(project_id="P1"),
|
||||
],
|
||||
)
|
||||
),
|
||||
), patch(
|
||||
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
|
||||
new=AsyncMock(return_value=[]),
|
||||
):
|
||||
result = await get_top_authors(ORG_INSTITUTION_ID, "Example Org")
|
||||
result = await get_top_authors(
|
||||
ORG_INSTITUTION_ID,
|
||||
"Example Org",
|
||||
)
|
||||
|
||||
assert result.works[0].name == "Ada Example"
|
||||
assert result.eu_projects == []
|
||||
@@ -556,6 +697,9 @@ async def test_top_authors_can_rank_works_by_last_five_years():
|
||||
), patch(
|
||||
"inse.dashboard.service.InstitutionsSearchClient.get_institution_aliases_by_oa_institution_id",
|
||||
new=AsyncMock(return_value=["Example University"]),
|
||||
), patch(
|
||||
"inse.dashboard.service.get_eu_organization_project_contributions",
|
||||
new=AsyncMock(return_value=SimpleNamespace(elements=[])),
|
||||
), patch(
|
||||
"inse.dashboard.service.OrgPatentsSearchClient.top_authors_by_institution",
|
||||
new=AsyncMock(return_value=[]),
|
||||
@@ -716,13 +860,15 @@ async def test_topic_heatmap_maps_field_year_counts_and_shares():
|
||||
== "topics.field.id"
|
||||
)
|
||||
assert (
|
||||
body["aggs"]["topics_nested"]["aggs"]["fields"]["aggs"]
|
||||
["subfields"]["terms"]["field"]
|
||||
body["aggs"]["topics_nested"]["aggs"]["fields"]["aggs"]["subfields"]["terms"][
|
||||
"field"
|
||||
]
|
||||
== "topics.subfield.id"
|
||||
)
|
||||
assert (
|
||||
body["aggs"]["topics_nested"]["aggs"]["fields"]["aggs"]
|
||||
["subfields"]["aggs"]["topics"]["terms"]["field"]
|
||||
body["aggs"]["topics_nested"]["aggs"]["fields"]["aggs"]["subfields"][
|
||||
"aggs"
|
||||
]["topics"]["terms"]["field"]
|
||||
== "topics.id"
|
||||
)
|
||||
subfield_aggs = body["aggs"]["topics_nested"]["aggs"]["fields"]["aggs"]
|
||||
@@ -734,7 +880,7 @@ async def test_topic_heatmap_maps_field_year_counts_and_shares():
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_topic_heatmap_defaults_to_last_five_years():
|
||||
async def test_topic_heatmap_defaults_to_all_time():
|
||||
async def search(**kwargs):
|
||||
if kwargs["index"] == config.settings.openalex_works_search_index:
|
||||
return {
|
||||
@@ -754,13 +900,9 @@ async def test_topic_heatmap_defaults_to_last_five_years():
|
||||
organization_name="Example Org",
|
||||
)
|
||||
|
||||
current_year = datetime.now().year
|
||||
assert result.years == list(range(current_year - 4, current_year + 1))
|
||||
assert result.years == []
|
||||
body = mocked_search.await_args_list[0].kwargs["body"]
|
||||
assert body["query"]["bool"]["filter"][0]["range"]["publication_year"] == {
|
||||
"gte": current_year - 4,
|
||||
"lte": current_year,
|
||||
}
|
||||
assert body["query"]["bool"]["filter"] == []
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
|
||||
@@ -2,7 +2,7 @@ from typing import Annotated
|
||||
|
||||
from fastapi import Depends
|
||||
from sqlalchemy import inspect, text
|
||||
from sqlmodel import SQLModel, Session, create_engine
|
||||
from sqlmodel import Session, SQLModel, create_engine
|
||||
|
||||
from inse import config
|
||||
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import logging
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Query
|
||||
import inse.institutions.v2.service as institutions_service
|
||||
from fastapi import APIRouter, Path, Query
|
||||
from inse.institutions.v2.model import InstitutionPageV2
|
||||
from inse.models.openalex.institution import Institution
|
||||
from inse.router_prefixes import RouterPrefixes
|
||||
from inse.tags import Tags
|
||||
|
||||
@@ -13,7 +15,32 @@ router = APIRouter(prefix=RouterPrefixes.INSTITUTIONS_V2, tags=[Tags.INSTITUTION
|
||||
|
||||
|
||||
@router.get(
|
||||
"/ids",
|
||||
"/single/{institution_id}",
|
||||
operation_id="getInstitutionById2",
|
||||
summary="Returns an institution based on its ID.",
|
||||
)
|
||||
async def get_institution_by_id(
|
||||
institution_id: Annotated[
|
||||
str,
|
||||
Path(description="The ID of the institution to retrieve."),
|
||||
],
|
||||
) -> Institution:
|
||||
return await institutions_service.get_institution_by_id_or_raise(
|
||||
raw_oa_institution_id=institution_id,
|
||||
source=[
|
||||
"id",
|
||||
"display_name",
|
||||
"display_name_alternatives",
|
||||
"works_count",
|
||||
"cited_by_count",
|
||||
"geo",
|
||||
"summary_stats",
|
||||
],
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/multiple/ids",
|
||||
operation_id="getInstitutionsByIds",
|
||||
summary="Returns a list of institutions based on their IDs.",
|
||||
)
|
||||
@@ -23,9 +50,9 @@ async def get_institutions_by_ids(
|
||||
Query(description="A list of institution IDs to retrieve."),
|
||||
] = None,
|
||||
) -> InstitutionPageV2:
|
||||
from inse.institutions.v2.service import get_institutions_by_ids
|
||||
|
||||
return await get_institutions_by_ids(institution_ids=institution_ids or [])
|
||||
return await institutions_service.get_institutions_by_ids(
|
||||
institution_ids=institution_ids or []
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
@@ -41,6 +68,6 @@ async def get_institution_autocomplete(
|
||||
),
|
||||
] = "",
|
||||
) -> InstitutionPageV2:
|
||||
from inse.institutions.v2.service import autocomplete_institutions_for_selector
|
||||
|
||||
return await autocomplete_institutions_for_selector(query=query)
|
||||
return await institutions_service.autocomplete_institutions_for_selector(
|
||||
query=query
|
||||
)
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import logging
|
||||
|
||||
from inse.exceptions import NotFoundException
|
||||
from inse.institutions.v2.model import InstitutionPageV2
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESIndex
|
||||
@@ -8,6 +9,51 @@ from inse.models.openalex.institution import Institution
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
async def get_institution_by_id(
|
||||
raw_oa_institution_id: str, source: list[str] | None = None
|
||||
) -> Institution | None:
|
||||
"""Retrieves an institution by its ID from the OpenAlex Elasticsearch index.
|
||||
|
||||
Args:
|
||||
raw_oa_institution_id (str): The raw OpenAlex ID of the institution to retrieve.
|
||||
source (Optional[List[str]], optional): A list of fields to include in the response. Defaults to None.
|
||||
|
||||
Returns:
|
||||
Institution | None: The institution object if found, otherwise None.
|
||||
"""
|
||||
response = await elasticsearch.get(
|
||||
index=ESIndex.OPENALEX_INSTITUTIONS, doc_id=raw_oa_institution_id, source=source
|
||||
)
|
||||
if not response.get("found"):
|
||||
return None
|
||||
return Institution.from_dict(response.get("_source", {})) # type: ignore
|
||||
|
||||
|
||||
async def get_institution_by_id_or_raise(
|
||||
raw_oa_institution_id: str, source: list[str] | None = None
|
||||
) -> Institution:
|
||||
"""Retrieves an institution by its ID from the OpenAlex Elasticsearch index, raising an exception if not found.
|
||||
|
||||
Args:
|
||||
raw_oa_institution_id (str): The raw OpenAlex ID of the institution to retrieve.
|
||||
source (Optional[List[str]], optional): A list of fields to include in the response. Defaults to None.
|
||||
|
||||
Raises:
|
||||
NotFoundException: If the institution is not found.
|
||||
|
||||
Returns:
|
||||
Institution: The institution object if found.
|
||||
"""
|
||||
institution = await get_institution_by_id(
|
||||
raw_oa_institution_id=raw_oa_institution_id, source=source
|
||||
)
|
||||
if institution is None:
|
||||
raise NotFoundException(
|
||||
f"Institution with ID {raw_oa_institution_id} not found."
|
||||
)
|
||||
return institution
|
||||
|
||||
|
||||
async def search_institutions(
|
||||
page: int = 0,
|
||||
size: int = 10,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import json
|
||||
import logging
|
||||
import time
|
||||
from typing import Any, Dict, AsyncIterator, List, Optional, Tuple
|
||||
|
||||
import httpx
|
||||
@@ -110,6 +111,10 @@ def _index_to_cluster(index: ESIndex) -> Optional[ESCluster]:
|
||||
return None
|
||||
|
||||
|
||||
def _headers(api_key: str, content_type: str = "application/json") -> Dict[str, str]:
|
||||
return {"Authorization": f"ApiKey {api_key}", "Content-Type": content_type}
|
||||
|
||||
|
||||
def _wrap_exception(e: Exception) -> Exception:
|
||||
logger.exception(f"Elasticsearch raised an exception: {e}")
|
||||
if isinstance(e, httpx.HTTPStatusError):
|
||||
@@ -125,6 +130,63 @@ def _wrap_exception(e: Exception) -> Exception:
|
||||
return ElasticsearchException(f"Unexpected Elasticsearch error: {e}")
|
||||
|
||||
|
||||
async def _request(
|
||||
method: str,
|
||||
cluster: ESCluster,
|
||||
path: str,
|
||||
*,
|
||||
json_body: Optional[Any] = None,
|
||||
params: Optional[Dict[str, Any]] = None,
|
||||
content: Optional[bytes] = None,
|
||||
content_type: str = "application/json",
|
||||
) -> httpx.Response:
|
||||
"""Sends an authenticated request to cluster and returns the raw response.
|
||||
|
||||
Args:
|
||||
method: The HTTP method (e.g. "GET", "POST", "PUT", "DELETE").
|
||||
cluster: The Elasticsearch cluster to send the request to.
|
||||
path: The path appended to the cluster URL (without leading slash).
|
||||
json_body: Optional JSON-serialisable request body.
|
||||
params: Optional query parameters.
|
||||
content: Optional raw request body (e.g. ndjson); mutually exclusive with json_body.
|
||||
content_type: The Content-Type header value.
|
||||
|
||||
Returns:
|
||||
httpx.Response: The successful response (status already checked).
|
||||
"""
|
||||
|
||||
elasticsearch_url, api_key = _cluster_credentials(cluster)
|
||||
client = get_client()
|
||||
|
||||
start = time.perf_counter()
|
||||
try:
|
||||
response = await client.request(
|
||||
method,
|
||||
f"{elasticsearch_url}/{path}",
|
||||
json=json_body,
|
||||
params=params,
|
||||
content=content,
|
||||
headers=_headers(api_key, content_type=content_type),
|
||||
)
|
||||
|
||||
response.raise_for_status()
|
||||
|
||||
if config.settings.print_es_timings:
|
||||
elapsed_ms = (time.perf_counter() - start) * 1000
|
||||
logger.debug(
|
||||
f"Elasticsearch request {method} {path} on cluster '{cluster}' took {elapsed_ms:.1f} ms"
|
||||
)
|
||||
|
||||
return response
|
||||
except Exception as exc:
|
||||
if config.settings.print_es_timings:
|
||||
elapsed_ms = (time.perf_counter() - start) * 1000
|
||||
logger.debug(
|
||||
f"Elasticsearch request {method} {path} on cluster '{cluster}' failed after {elapsed_ms:.1f} ms"
|
||||
)
|
||||
raise _wrap_exception(exc) from exc
|
||||
|
||||
|
||||
async def search(
|
||||
index: ESIndex | List[ESIndex] | str | List[str],
|
||||
query: Optional[Dict] = None,
|
||||
@@ -175,10 +237,6 @@ async def search(
|
||||
elif len(clusters) == 1:
|
||||
cluster = clusters.pop()
|
||||
|
||||
elasticsearch_url, api_key = _cluster_credentials(cluster)
|
||||
|
||||
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
|
||||
|
||||
payload: Dict[str, Any] = {}
|
||||
|
||||
if body is not None:
|
||||
@@ -210,61 +268,34 @@ async def search(
|
||||
"At least one of 'query', 'body', 'source', 'size', 'offset', 'sort', 'aggs' must be provided"
|
||||
)
|
||||
|
||||
client = get_client()
|
||||
logger.debug(
|
||||
f"Sending search request to Elasticsearch cluster '{cluster}' at {elasticsearch_url} for {index} with payload: {json.dumps(payload)}"
|
||||
)
|
||||
if config.settings.print_es_queries:
|
||||
logger.debug(
|
||||
f"Sending search request to Elasticsearch cluster '{cluster}' for {index} with payload: {json.dumps(payload)}"
|
||||
)
|
||||
|
||||
if isinstance(index, list):
|
||||
index_str = ",".join(str(idx) for idx in index)
|
||||
else:
|
||||
index_str = str(index)
|
||||
|
||||
try:
|
||||
response = await client.post(
|
||||
f"{elasticsearch_url}/{index_str}/_search", json=payload, headers=headers
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
except Exception as exc:
|
||||
raise _wrap_exception(exc) from exc
|
||||
response = await _request("POST", cluster, f"{index_str}/_search", json_body=payload)
|
||||
|
||||
return response.json()
|
||||
|
||||
|
||||
async def open_point_in_time(
|
||||
index: str, keep_alive: str = "1m", cluster: str = "nes"
|
||||
) -> str:
|
||||
"""Opens a point-in-time on the given index and returns its id."""
|
||||
elasticsearch_url, api_key = _cluster_credentials(cluster)
|
||||
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
|
||||
response = await _request("POST", cluster, f"{index}/_pit", params={"keep_alive": keep_alive})
|
||||
|
||||
client = get_client()
|
||||
try:
|
||||
response = await client.post(
|
||||
f"{elasticsearch_url}/{index}/_pit",
|
||||
params={"keep_alive": keep_alive},
|
||||
headers=headers,
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()["id"]
|
||||
except Exception as exc:
|
||||
raise _wrap_exception(exc) from exc
|
||||
return response.json()["id"]
|
||||
|
||||
|
||||
async def close_point_in_time(pit_id: str, cluster: str = "nes") -> None:
|
||||
"""Closes a previously opened point-in-time."""
|
||||
elasticsearch_url, api_key = _cluster_credentials(cluster)
|
||||
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
|
||||
|
||||
client = get_client()
|
||||
try:
|
||||
response = await client.request(
|
||||
"DELETE",
|
||||
f"{elasticsearch_url}/_pit",
|
||||
json={"id": pit_id},
|
||||
headers=headers,
|
||||
)
|
||||
response.raise_for_status()
|
||||
except Exception as exc:
|
||||
raise _wrap_exception(exc) from exc
|
||||
await _request("DELETE", cluster, "_pit", json_body={"id": pit_id})
|
||||
|
||||
|
||||
async def scan(
|
||||
@@ -280,13 +311,9 @@ async def scan(
|
||||
Unlike ``from``/``size`` pagination, this is not bounded by
|
||||
``index.max_result_window``, so it can stream result sets larger than 10k.
|
||||
"""
|
||||
elasticsearch_url, api_key = _cluster_credentials(cluster)
|
||||
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
|
||||
|
||||
pit_id = await open_point_in_time(index, keep_alive=keep_alive, cluster=cluster)
|
||||
search_after: Optional[List] = None
|
||||
try:
|
||||
client = get_client()
|
||||
while True:
|
||||
payload: Dict[str, Any] = {
|
||||
"size": page_size,
|
||||
@@ -299,14 +326,7 @@ async def scan(
|
||||
if search_after is not None:
|
||||
payload["search_after"] = search_after
|
||||
|
||||
try:
|
||||
response = await client.post(
|
||||
f"{elasticsearch_url}/_search", json=payload, headers=headers
|
||||
)
|
||||
response.raise_for_status()
|
||||
except Exception as exc:
|
||||
raise _wrap_exception(exc) from exc
|
||||
|
||||
response = await _request("POST", cluster, "_search", json_body=payload)
|
||||
result = response.json()
|
||||
|
||||
hits = result.get("hits", {}).get("hits", [])
|
||||
@@ -338,23 +358,13 @@ async def get(
|
||||
if isinstance(index, ESIndex):
|
||||
cluster = _index_to_cluster(index) or cluster
|
||||
|
||||
elasticsearch_url, api_key = _cluster_credentials(cluster)
|
||||
|
||||
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
|
||||
|
||||
params = {}
|
||||
if source is not None:
|
||||
params["_source_includes"] = ",".join(source)
|
||||
|
||||
client = get_client()
|
||||
try:
|
||||
response = await client.get(
|
||||
f"{elasticsearch_url}/{index}/_doc/{doc_id}", params=params, headers=headers
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
except Exception as exc:
|
||||
raise _wrap_exception(exc) from exc
|
||||
response = await _request("GET", cluster, f"{index}/_doc/{doc_id}", params=params)
|
||||
|
||||
return response.json()
|
||||
|
||||
|
||||
async def update(
|
||||
@@ -363,20 +373,11 @@ async def update(
|
||||
doc: Dict[str, Any],
|
||||
cluster: ESCluster = ESCluster.NES,
|
||||
) -> Dict[str, Any]:
|
||||
elasticsearch_url, api_key = _cluster_credentials(cluster)
|
||||
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
|
||||
response = await _request(
|
||||
"POST", cluster, f"{index}/_update/{doc_id}", json_body={"doc": doc}
|
||||
)
|
||||
|
||||
client = get_client()
|
||||
try:
|
||||
response = await client.post(
|
||||
f"{elasticsearch_url}/{index}/_update/{doc_id}",
|
||||
json={"doc": doc},
|
||||
headers=headers,
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
except Exception as exc:
|
||||
raise _wrap_exception(exc) from exc
|
||||
return response.json()
|
||||
|
||||
|
||||
async def index_doc(
|
||||
@@ -385,20 +386,11 @@ async def index_doc(
|
||||
document: Dict[str, Any],
|
||||
cluster: ESCluster = ESCluster.NES,
|
||||
) -> Dict[str, Any]:
|
||||
elasticsearch_url, api_key = _cluster_credentials(cluster)
|
||||
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
|
||||
response = await _request(
|
||||
"PUT", cluster, f"{index}/_doc/{doc_id}", json_body=document
|
||||
)
|
||||
|
||||
client = get_client()
|
||||
try:
|
||||
response = await client.put(
|
||||
f"{elasticsearch_url}/{index}/_doc/{doc_id}",
|
||||
json=document,
|
||||
headers=headers,
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()
|
||||
except Exception as exc:
|
||||
raise _wrap_exception(exc) from exc
|
||||
return response.json()
|
||||
|
||||
|
||||
async def count(
|
||||
@@ -431,24 +423,15 @@ async def count(
|
||||
if len(clusters) == 1:
|
||||
cluster = clusters.pop()
|
||||
|
||||
elasticsearch_url, api_key = _cluster_credentials(cluster)
|
||||
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/json"}
|
||||
|
||||
if isinstance(index, list):
|
||||
index_str = ",".join(str(idx) for idx in index)
|
||||
else:
|
||||
index_str = str(index)
|
||||
|
||||
payload = {"query": query} if query else {}
|
||||
client = get_client()
|
||||
try:
|
||||
response = await client.post(
|
||||
f"{elasticsearch_url}/{index_str}/_count", json=payload, headers=headers
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json().get("count", 0)
|
||||
except Exception as exc:
|
||||
raise _wrap_exception(exc) from exc
|
||||
response = await _request("POST", cluster, f"{index_str}/_count", json_body=payload)
|
||||
|
||||
return response.json().get("count", 0)
|
||||
|
||||
|
||||
async def msearch(
|
||||
@@ -473,9 +456,6 @@ async def msearch(
|
||||
if c is not None:
|
||||
cluster = c
|
||||
|
||||
elasticsearch_url, api_key = _cluster_credentials(cluster)
|
||||
headers = {"Authorization": f"ApiKey {api_key}", "Content-Type": "application/x-ndjson"}
|
||||
|
||||
lines = []
|
||||
for idx, body in searches:
|
||||
if isinstance(idx, list):
|
||||
@@ -488,16 +468,13 @@ async def msearch(
|
||||
|
||||
ndjson_payload = "\n".join(lines) + "\n"
|
||||
|
||||
client = get_client()
|
||||
try:
|
||||
response = await client.post(
|
||||
f"{elasticsearch_url}/_msearch",
|
||||
content=ndjson_payload.encode("utf-8"),
|
||||
headers=headers,
|
||||
)
|
||||
response.raise_for_status()
|
||||
res_json = response.json()
|
||||
return res_json.get("responses", [])
|
||||
except Exception as exc:
|
||||
raise _wrap_exception(exc) from exc
|
||||
response = await _request(
|
||||
"POST",
|
||||
cluster,
|
||||
"_msearch",
|
||||
content=ndjson_payload.encode("utf-8"),
|
||||
content_type="application/x-ndjson",
|
||||
)
|
||||
|
||||
return response.json().get("responses", [])
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
This module contains the bootstrapping code
|
||||
for fastapi that loads the service and the
|
||||
@@ -7,65 +6,65 @@ webapp.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
from contextlib import asynccontextmanager, contextmanager
|
||||
import logging
|
||||
from contextlib import asynccontextmanager, contextmanager
|
||||
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import JSONResponse, RedirectResponse
|
||||
|
||||
from inse.collaboration_network.router import router as collaboration_network_router
|
||||
from inse.account_management.router import router as account_management_router
|
||||
from inse.auth.router import router as auth_router
|
||||
from inse.auth.service import create_predefined_accounts
|
||||
from inse.authors.v2.router import router as authors_v2_router
|
||||
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 inse.bookmarks.router import router as bookmarks_router
|
||||
from inse.company_connections.service import router as company_connections_router
|
||||
from inse.dashboard.router import router as dashboard_router
|
||||
from inse.database import create_db_and_tables, get_session
|
||||
from inse.exceptions import (
|
||||
NotFoundException,
|
||||
BadRequestException,
|
||||
ElasticsearchException,
|
||||
MissingApiKeyError,
|
||||
NotFoundException,
|
||||
UpstreamAPIException,
|
||||
BadRequestException,
|
||||
)
|
||||
from inse.funders.service import router as funders_service_router
|
||||
from inse.projects.router import router as projects_router
|
||||
from inse.ranking.router import router as ranking_router
|
||||
from inse.university_ranking.service import router as university_ranking_router
|
||||
from inse.institutions.router import router as institutions_router
|
||||
from inse.institutions.v2.router import router as institutions_v2_router
|
||||
from inse.keywords.service import router as keywords_service_router
|
||||
from inse.patents.keywords.service import router as keywords_patents_router
|
||||
|
||||
# caching
|
||||
from inse.middleware.etag_cache import ETagCacheMiddleware
|
||||
from inse.persons.service import router as persons_service_router
|
||||
from inse.topics.service import router as topics_service_router
|
||||
from inse.works.service import router as works_service_router
|
||||
from inse.news.service import router as news_service_router
|
||||
from inse.auth.router import router as auth_router
|
||||
from inse.account_management.router import router as account_management_router
|
||||
from inse.organization_management.router import router as organization_management_router
|
||||
from inse.dashboard.router import router as dashboard_router
|
||||
from inse.bookmarks.router import router as bookmarks_router
|
||||
|
||||
from inse.institutions.router import router as institutions_router
|
||||
from inse.database import create_db_and_tables, get_session
|
||||
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 .service import router as service_router
|
||||
from inse.patents.keywords.service import router as keywords_patents_router
|
||||
from inse.patents.org.service import router as org_patents_router
|
||||
from inse.patents.service import (
|
||||
institution_patents_router,
|
||||
)
|
||||
from inse.patents.service import (
|
||||
patents_router as patents_all_router,
|
||||
)
|
||||
from inse.patents.service import (
|
||||
router as patents_service_router,
|
||||
)
|
||||
|
||||
from inse.works.v2.router import router as works_v2_router
|
||||
from inse.authors.v2.router import router as authors_v2_router
|
||||
from inse.institutions.v2.router import router as institutions_v2_router
|
||||
from inse.topics.v2.router import router as topics_v2_router
|
||||
|
||||
from inse.persons.service import router as persons_service_router
|
||||
from inse.projects.dfg_institutions.router import router as dfg_institutions_router
|
||||
from inse.projects.bund_institutions.router import router as bund_institutions_router
|
||||
from inse.projects.dfg_persons.router import router as dfg_persons_router
|
||||
|
||||
from inse.projects.eu_organizations.router import router as eu_organizations_router
|
||||
from inse.projects.router import router as projects_router
|
||||
from inse.ranking.router import router as ranking_router
|
||||
from inse.topics.service import router as topics_service_router
|
||||
from inse.topics.v2.router import router as topics_v2_router
|
||||
from inse.university_ranking.service import router as university_ranking_router
|
||||
from inse.works.service import router as works_service_router
|
||||
from inse.works.v2.router import router as works_v2_router
|
||||
|
||||
from . import config
|
||||
from .service import router as service_router
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -102,10 +101,10 @@ app = FastAPI(
|
||||
servers=settings.servers,
|
||||
lifespan=lifespan,
|
||||
)
|
||||
app.include_router(collaboration_network_router)
|
||||
app.include_router(institution_patents_router)
|
||||
app.include_router(org_patents_router)
|
||||
app.include_router(institutions_router)
|
||||
app.include_router(bund_institutions_router)
|
||||
app.include_router(topics_service_router)
|
||||
app.include_router(works_service_router)
|
||||
app.include_router(persons_service_router)
|
||||
@@ -140,7 +139,7 @@ app.include_router(background_jobs_router)
|
||||
app.include_router(eu_organizations_router)
|
||||
app.add_middleware(
|
||||
ETagCacheMiddleware,
|
||||
ttl=120, # 2 minutes expiration time
|
||||
ttl=600, # 10 minutes expiration time
|
||||
)
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
|
||||
@@ -16,14 +16,16 @@ NO_STORE_PATH_PREFIXES = (
|
||||
"/api/background-jobs",
|
||||
"/api/bookmarks",
|
||||
"/api/organizations",
|
||||
"/api/dashboard",
|
||||
"/api/rank/rank-author",
|
||||
"/api/works/v2/classification/",
|
||||
)
|
||||
"/api/dashboard",
|
||||
"/api/rank/rank-author",
|
||||
"/api/rank/orientation-profiles",
|
||||
"/api/works/v2/classification/",
|
||||
)
|
||||
|
||||
NO_STORE_PATH_FRAGMENTS = (
|
||||
"/company-connections",
|
||||
"/primary-category-aggregations",
|
||||
"/collaboration-graph/",
|
||||
)
|
||||
# POST is opt-out. Add any endpoint here that MUTATES state (create/update/delete/
|
||||
# trigger side effects), even if it "usually" returns 200.
|
||||
@@ -41,7 +43,7 @@ class ETagCacheMiddleware(BaseHTTPMiddleware):
|
||||
self.ttl = ttl
|
||||
self.maxsize = maxsize
|
||||
# Insertion-ordered so we can evict the oldest entry in O(1) when over capacity.
|
||||
self.cache: "OrderedDict[str, dict]" = OrderedDict()
|
||||
self.cache: OrderedDict[str, dict] = OrderedDict()
|
||||
|
||||
def _get(self, key: str) -> dict | None:
|
||||
entry = self.cache.get(key)
|
||||
|
||||
@@ -66,6 +66,11 @@ class ESIndex(StrEnum):
|
||||
DFG_INSTITUTES_V2 = "dfg_institutes_2.0"
|
||||
PROJECTS_DFG_OPENALEX_TOPICS = "projects_dfg_openalex_topics"
|
||||
|
||||
AKTUELLES = "aktuell"
|
||||
AKTUELLES_POSTPROC = "aktuell_postproc"
|
||||
AKTUELLES_OPENALEX_TOPICS = "aktuell_openalex_topics"
|
||||
|
||||
|
||||
CORDIS_EU_ORGANIZATIONS_WILDCARD = "cordis_eu_*_organizations"
|
||||
CORDIS_EU_PROJECTS_WILDCARD = "cordis_eu_*_projects"
|
||||
CORDIS_EU_PUBLICATIONS_WILDCARD = "cordis_eu_*_publications"
|
||||
|
||||
@@ -8,8 +8,8 @@
|
||||
"""
|
||||
|
||||
from datetime import date, datetime
|
||||
from typing import Optional, List, Set, Any
|
||||
|
||||
from typing import Optional, List, Set, Any, Dict
|
||||
from inse.models.openalex.topic import Topic, TopicDomain, TopicField, TopicSubfield
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||
|
||||
|
||||
@@ -189,6 +189,10 @@ class BundProjectDetails(BaseModel):
|
||||
default_factory=list,
|
||||
description="All institutions associated with the Bund project",
|
||||
)
|
||||
oa_topics: Optional[List[Topic]] = Field(
|
||||
default_factory=list,
|
||||
description="OpenAlex topics associated with the Bund project",
|
||||
)
|
||||
|
||||
# --- Validators for type coercion ---
|
||||
|
||||
@@ -301,7 +305,17 @@ class BundProjectDetails(BaseModel):
|
||||
|
||||
if source.get("PT_fullname"):
|
||||
institutions.add(source["PT_fullname"].strip())
|
||||
topics_raw = source.get("oa_topics") or []
|
||||
if not isinstance(source, dict):
|
||||
return cls.model_validate(source)
|
||||
oa_topics = None
|
||||
if isinstance(topics_raw, list) and topics_raw:
|
||||
|
||||
sorted_topics_raw = sorted(
|
||||
(t for t in topics_raw if isinstance(t, dict)),
|
||||
key=lambda t: t.get("rank") if t.get("rank") is not None else float("inf"),
|
||||
)
|
||||
oa_topics = [cls._topic_from_match(t) for t in sorted_topics_raw]
|
||||
return cls(
|
||||
id=hit["_id"],
|
||||
funding_reference=source.get("Förderkennzeichen"),
|
||||
@@ -334,4 +348,24 @@ class BundProjectDetails(BaseModel):
|
||||
unix_timestamp=source.get("unix_timestamp"),
|
||||
associated_persons=sorted(persons),
|
||||
institutions=sorted(institutions),
|
||||
oa_topics=oa_topics
|
||||
)
|
||||
@staticmethod
|
||||
def _topic_from_match(match: Dict[str, Any]) -> Topic:
|
||||
"""Builds a Topic model from a flattened topic_match dict.
|
||||
"""
|
||||
domain_name = match.get("domain")
|
||||
field_name = match.get("field")
|
||||
subfield_name = match.get("subfield")
|
||||
|
||||
domain = TopicDomain(display_name=domain_name) if domain_name else None
|
||||
field = TopicField(display_name=field_name) if field_name else None
|
||||
subfield = TopicSubfield(display_name=subfield_name) if subfield_name else None
|
||||
|
||||
return Topic(
|
||||
id=match.get("topic_id"),
|
||||
display_name=match.get("topic_display_name"),
|
||||
domain=domain,
|
||||
field=field,
|
||||
subfield=subfield,
|
||||
)
|
||||
@@ -1,293 +1,435 @@
|
||||
# coding: utf-8
|
||||
|
||||
"""
|
||||
DFG Project Clean Model
|
||||
DFG Project Clean Model (v2)
|
||||
|
||||
Summary model that consolidates all scattered person and institution fields
|
||||
from the raw projects_dfg_all index into clean, unified lists.
|
||||
Enriched, consolidated model built on top of the structured
|
||||
projects_dfg_v2 API models (DFGProject / DFGPerson / DFGInstitute),
|
||||
rather than the old flat projects_dfg_all Elasticsearch index.
|
||||
"""
|
||||
|
||||
from typing import Optional, List, Set
|
||||
from typing import List, Optional
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from inse.models.projects_dfg_v2.project.dfg_project import DFGProject
|
||||
from inse.models.projects_dfg_v2.project.dfg_project_persons_inner import (
|
||||
DFGProjectPersonsInner,
|
||||
)
|
||||
from inse.models.projects_dfg_v2.project.dfg_project_institutions_inner import (
|
||||
DFGProjectInstitutionsInner,
|
||||
)
|
||||
from inse.models.projects_dfg_v2.project.dfg_project_subprojects_inner import (
|
||||
DFGProjectSubprojectsInner,
|
||||
)
|
||||
from inse.models.projects_dfg_v2.project.dfg_project_publications_inner import (
|
||||
DFGProjectPublicationsInner,
|
||||
)
|
||||
from inse.models.projects_dfg_v2.project.dfg_project_fachgebiete_inner import (
|
||||
DFGProjectFachgebieteInner,
|
||||
)
|
||||
from inse.topics.model import Topic
|
||||
|
||||
|
||||
class DfgProjectPersonRole(BaseModel):
|
||||
"""A person associated with the project, together with their role."""
|
||||
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
person_id: Optional[int] = Field(default=None, description="DFG person ID")
|
||||
full_name: Optional[str] = Field(default=None, description="Full name of the person")
|
||||
orcid_id: Optional[str] = Field(
|
||||
default=None,
|
||||
description=(
|
||||
"ORCID iD, if known. Not present on the project's embedded person "
|
||||
"record (DFGProjectPersonsInner) -- only populated if the caller "
|
||||
"cross-references the full DFGPerson record via person_id and "
|
||||
"calls DfgProjectDetails.enrich_orcids afterwards."
|
||||
),
|
||||
)
|
||||
role_key: Optional[str] = Field(
|
||||
default=None, description="Machine-readable role key (e.g. 'antragsteller')"
|
||||
)
|
||||
role_label_de: Optional[str] = Field(default=None, description="Role label (German)")
|
||||
role_label_en: Optional[str] = Field(default=None, description="Role label (English)")
|
||||
affiliation_de: Optional[str] = Field(
|
||||
default=None, description="Person's affiliation at time of project (German)"
|
||||
)
|
||||
affiliation_en: Optional[str] = Field(
|
||||
default=None, description="Person's affiliation at time of project (English)"
|
||||
)
|
||||
is_deceased: Optional[bool] = Field(default=None, description="Whether the person is deceased")
|
||||
is_head: Optional[bool] = Field(
|
||||
default=None, description="Whether this person is highlighted as the project head"
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def from_inner(cls, p: DFGProjectPersonsInner) -> "DfgProjectPersonRole":
|
||||
return cls(
|
||||
person_id=p.person_id,
|
||||
full_name=p.full_name,
|
||||
role_key=p.role_key,
|
||||
role_label_de=p.role_label_de,
|
||||
role_label_en=p.role_label_en,
|
||||
affiliation_de=p.affiliation_de,
|
||||
affiliation_en=p.affiliation_en,
|
||||
is_deceased=p.is_deceased,
|
||||
is_head=p.is_head_display,
|
||||
)
|
||||
|
||||
|
||||
class DfgProjectInstitutionRole(BaseModel):
|
||||
"""An institution associated with the project, together with its role."""
|
||||
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
institute_id: Optional[int] = Field(default=None, description="DFG institute ID")
|
||||
name_de: Optional[str] = Field(default=None, description="Institution name (German)")
|
||||
name_en: Optional[str] = Field(default=None, description="Institution name (English)")
|
||||
role_key: Optional[str] = Field(default=None, description="Machine-readable role key")
|
||||
role_label_de: Optional[str] = Field(default=None, description="Role label (German)")
|
||||
role_label_en: Optional[str] = Field(default=None, description="Role label (English)")
|
||||
is_dissolved: Optional[bool] = Field(
|
||||
default=None, description="Whether the institution has since been dissolved"
|
||||
)
|
||||
is_head: Optional[bool] = Field(
|
||||
default=None, description="Whether this institution is highlighted as the lead institution"
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def from_inner(cls, i: DFGProjectInstitutionsInner) -> "DfgProjectInstitutionRole":
|
||||
return cls(
|
||||
institute_id=i.institute_id,
|
||||
name_de=i.institute_name_de,
|
||||
name_en=i.institute_name_en,
|
||||
role_key=i.role_key,
|
||||
role_label_de=i.role_label_de,
|
||||
role_label_en=i.role_label_en,
|
||||
is_dissolved=i.is_dissolved,
|
||||
is_head=i.is_head_display,
|
||||
)
|
||||
|
||||
|
||||
class DfgProjectSubprojectSummary(BaseModel):
|
||||
"""A lightweight reference to a sub-project of this project."""
|
||||
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
subproject_id: Optional[int] = None
|
||||
title_de: Optional[str] = None
|
||||
title_en: Optional[str] = None
|
||||
short_title: Optional[str] = None
|
||||
role_label_de: Optional[str] = Field(
|
||||
default=None, description="Role of the sub-project lead within the sub-project"
|
||||
)
|
||||
person_full_name: Optional[str] = Field(
|
||||
default=None, description="Sub-project lead, derived from first/last name fields"
|
||||
)
|
||||
status_de: Optional[str] = None
|
||||
funding_start: Optional[int] = None
|
||||
funding_end: Optional[int] = None
|
||||
|
||||
@classmethod
|
||||
def from_inner(cls, s: DFGProjectSubprojectsInner) -> "DfgProjectSubprojectSummary":
|
||||
person_full_name = None
|
||||
if s.person_first_names or s.person_last_name:
|
||||
person_full_name = " ".join(
|
||||
part for part in [s.person_first_names, s.person_last_name] if part
|
||||
).strip() or None
|
||||
|
||||
return cls(
|
||||
subproject_id=s.subproject_id,
|
||||
title_de=s.title_de,
|
||||
title_en=s.title_en,
|
||||
short_title=s.short_title,
|
||||
role_label_de=s.role_label_de,
|
||||
person_full_name=person_full_name,
|
||||
status_de=s.status_de,
|
||||
funding_start=s.funding_start,
|
||||
funding_end=s.funding_end,
|
||||
)
|
||||
|
||||
|
||||
class DfgProjectPublicationSummary(BaseModel):
|
||||
"""A lightweight reference to a publication resulting from the project."""
|
||||
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
publication_id: Optional[int] = None
|
||||
title: Optional[str] = None
|
||||
authors_editors: Optional[str] = None
|
||||
doi: Optional[str] = None
|
||||
publication_year: Optional[int] = None
|
||||
|
||||
@classmethod
|
||||
def from_inner(cls, p: DFGProjectPublicationsInner) -> "DfgProjectPublicationSummary":
|
||||
return cls(
|
||||
publication_id=p.publication_id,
|
||||
title=p.title,
|
||||
authors_editors=p.authors_editors,
|
||||
doi=p.doi,
|
||||
publication_year=p.publication_year,
|
||||
)
|
||||
|
||||
|
||||
class DfgProjectSubjectArea(BaseModel):
|
||||
"""A single subject-area classification entry (DFG 'Fachsystematik')."""
|
||||
|
||||
model_config = ConfigDict(populate_by_name=True)
|
||||
|
||||
fach: Optional[str] = None
|
||||
fachgebiet: Optional[str] = None
|
||||
fachkollegium: Optional[str] = None
|
||||
wissenschaftsbereich: Optional[str] = None
|
||||
|
||||
@classmethod
|
||||
def from_inner(cls, f: DFGProjectFachgebieteInner) -> "DfgProjectSubjectArea":
|
||||
return cls(
|
||||
fach=f.fach,
|
||||
fachgebiet=f.fachgebiet,
|
||||
fachkollegium=f.fachkollegium,
|
||||
wissenschaftsbereich=f.wissenschaftsbereich,
|
||||
)
|
||||
|
||||
|
||||
class DfgProjectDetails(BaseModel):
|
||||
"""
|
||||
Clean summary model for a DFG project, consolidating all person roles
|
||||
and institution references into unified lists.
|
||||
Clean, enriched summary model for a DFG project.
|
||||
"""
|
||||
model_config = ConfigDict(
|
||||
populate_by_name=True,
|
||||
validate_assignment=True,
|
||||
|
||||
model_config = ConfigDict(populate_by_name=True, validate_assignment=True)
|
||||
|
||||
id: Optional[int] = Field(default=None, description="The DFG project ID")
|
||||
link: Optional[str] = Field(default=None, description="Canonical DFG link to the project")
|
||||
page_url: Optional[str] = Field(default=None, description="DFG GEPRIS page URL")
|
||||
external_link: Optional[str] = Field(
|
||||
default=None, description="External project website/link, if provided"
|
||||
)
|
||||
|
||||
id: str = Field(description="The ID of the DFG project")
|
||||
link: Optional[str] = Field(default=None, description="The link to the DFG project")
|
||||
title: Optional[str] = Field(
|
||||
default=None, description="The title of the DFG project"
|
||||
title_de: Optional[str] = Field(default=None, description="Project title (German)")
|
||||
title_en: Optional[str] = Field(default=None, description="Project title (English)")
|
||||
description_de: Optional[str] = Field(default=None, description="Project abstract (German)")
|
||||
description_en: Optional[str] = Field(default=None, description="Project abstract (English)")
|
||||
final_report_abstract_de: Optional[str] = Field(
|
||||
default=None, description="Final report abstract (German), if the project has concluded"
|
||||
)
|
||||
description: Optional[str] = Field(
|
||||
default=None, description="The description of the DFG project"
|
||||
final_report_abstract_en: Optional[str] = Field(
|
||||
default=None, description="Final report abstract (English), if the project has concluded"
|
||||
)
|
||||
|
||||
project_identifier: Optional[str] = Field(
|
||||
default=None,
|
||||
description="The project identifier of the DFG project",
|
||||
)
|
||||
project_identifier_de: Optional[str] = Field(default=None, description="DFG project identifier (German)")
|
||||
project_identifier_en: Optional[str] = Field(default=None, description="DFG project identifier (English)")
|
||||
|
||||
funding_start_date: Optional[str] = Field(
|
||||
default=None, description="The funding start date of the DFG project"
|
||||
)
|
||||
funding_end_date: Optional[str] = Field(
|
||||
default=None, description="The funding end date of the DFG project"
|
||||
)
|
||||
funding_start: Optional[int] = Field(default=None, description="Funding start year")
|
||||
funding_end: Optional[int] = Field(default=None, description="Funding end year")
|
||||
funding_period_de: Optional[str] = Field(default=None, description="Human-readable funding period (German)")
|
||||
funding_period_en: Optional[str] = Field(default=None, description="Human-readable funding period (English)")
|
||||
|
||||
funding_type_de: Optional[str] = Field(default=None, description="Funding type / programme (German)")
|
||||
funding_type_en: Optional[str] = Field(default=None, description="Funding type / programme (English)")
|
||||
funding_type_key: Optional[str] = Field(default=None, description="Machine-readable funding type key")
|
||||
|
||||
dfg_procedure: Optional[str] = Field(
|
||||
default=None, description="The DFG procedure"
|
||||
)
|
||||
subject_area: Optional[str] = Field(
|
||||
default=None,
|
||||
description="The subject area classification",
|
||||
)
|
||||
funding_type: Optional[str] = Field(
|
||||
default=None, description="The type of funding"
|
||||
)
|
||||
international_reference: Optional[str] = Field(
|
||||
default=None,
|
||||
|
||||
description="International reference",
|
||||
default=None, description="DFG procedure / template type (e.g. Sachbeihilfe, SFB, GRK)"
|
||||
)
|
||||
|
||||
website: Optional[str] = Field(
|
||||
default=None, description="The project website"
|
||||
is_transfer_project: Optional[bool] = Field(
|
||||
default=None, description="Whether this is a transfer project"
|
||||
)
|
||||
|
||||
# Unified person list: all person names from any role
|
||||
website_html_de: Optional[str] = Field(
|
||||
default=None, description="Raw project website HTML content (German), as served by DFG"
|
||||
)
|
||||
website_html_en: Optional[str] = Field(
|
||||
default=None, description="Raw project website HTML content (English), as served by DFG"
|
||||
)
|
||||
|
||||
equipment_group: Optional[str] = Field(
|
||||
default=None,
|
||||
description="Large-equipment (Großgerät) group, for equipment-funding projects",
|
||||
)
|
||||
equipment_name: Optional[str] = Field(
|
||||
default=None,
|
||||
description="Large-equipment (Großgerät) name, for equipment-funding projects",
|
||||
)
|
||||
|
||||
subject_area_de: Optional[str] = Field(default=None, description="Subject area, summary text (German)")
|
||||
subject_area_en: Optional[str] = Field(default=None, description="Subject area, summary text (English)")
|
||||
subject_classifications: List[DfgProjectSubjectArea] = Field(
|
||||
default_factory=list,
|
||||
description="Detailed DFG subject-area classification entries (Fachsystematik)",
|
||||
)
|
||||
|
||||
international_relation_de: Optional[str] = Field(
|
||||
default=None, description="International reference/cooperation (German)"
|
||||
)
|
||||
international_relation_en: Optional[str] = Field(
|
||||
default=None, description="International reference/cooperation (English)"
|
||||
)
|
||||
|
||||
# Structured, role-aware person and institution lists
|
||||
persons: List[DfgProjectPersonRole] = Field(
|
||||
default_factory=list,
|
||||
description="All persons associated with the project, each with their role",
|
||||
)
|
||||
institutions: List[DfgProjectInstitutionRole] = Field(
|
||||
default_factory=list,
|
||||
description="All institutions associated with the project, each with their role",
|
||||
)
|
||||
|
||||
# Convenience flat views, derived from the structured lists above
|
||||
associated_persons: List[str] = Field(
|
||||
default_factory=list,
|
||||
description="All persons associated with the DFG project (any role)",
|
||||
description="Flat, de-duplicated list of all person full names (convenience view)",
|
||||
)
|
||||
|
||||
# Unified institution list: all institutions involved
|
||||
institutions: List[str] = Field(
|
||||
associated_institutions: List[str] = Field(
|
||||
default_factory=list,
|
||||
description="All institutions associated with the DFG project",
|
||||
description="Flat, de-duplicated list of all institution names (convenience view)",
|
||||
)
|
||||
|
||||
# Sub-project reference
|
||||
subproject_of: Optional[str] = Field(
|
||||
default=None,
|
||||
description="Parent project this is a sub-project of",
|
||||
# Parent / sub-project structure
|
||||
parent_project_id: Optional[int] = Field(default=None, description="Parent project ID, if this is a sub-project")
|
||||
parent_title_de: Optional[str] = Field(default=None, description="Parent project title (German)")
|
||||
parent_title_en: Optional[str] = Field(default=None, description="Parent project title (English)")
|
||||
subprojects: List[DfgProjectSubprojectSummary] = Field(
|
||||
default_factory=list, description="Sub-projects of this project, if any"
|
||||
)
|
||||
|
||||
publications: List[DfgProjectPublicationSummary] = Field(
|
||||
default_factory=list, description="Publications resulting from the project"
|
||||
)
|
||||
|
||||
topics: Optional[List[Topic]] = Field(
|
||||
default_factory=list, description="OpenAlex topics associated with the project ID"
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def from_dfg_project(cls, project: DFGProject) -> "DfgProjectDetails":
|
||||
"""
|
||||
Build a DfgProjectDetails from a fully-typed DFGProject instance
|
||||
(e.g. as returned by the projects_dfg_v2 API client).
|
||||
"""
|
||||
|
||||
persons = [DfgProjectPersonRole.from_inner(p) for p in (project.persons or [])]
|
||||
institutions = [
|
||||
DfgProjectInstitutionRole.from_inner(i) for i in (project.institutions or [])
|
||||
]
|
||||
subprojects = [
|
||||
DfgProjectSubprojectSummary.from_inner(s) for s in (project.subprojects or [])
|
||||
]
|
||||
publications = [
|
||||
DfgProjectPublicationSummary.from_inner(p) for p in (project.publications or [])
|
||||
]
|
||||
subject_classifications = [
|
||||
DfgProjectSubjectArea.from_inner(f) for f in (project.fachgebiete or [])
|
||||
]
|
||||
|
||||
# De-duplicated flat views, order-preserving
|
||||
seen_persons = set()
|
||||
associated_persons = []
|
||||
for p in persons:
|
||||
if p.full_name and p.full_name not in seen_persons:
|
||||
seen_persons.add(p.full_name)
|
||||
associated_persons.append(p.full_name)
|
||||
|
||||
seen_institutions = set()
|
||||
associated_institutions = []
|
||||
for i in institutions:
|
||||
name = i.name_de or i.name_en
|
||||
if name and name not in seen_institutions:
|
||||
seen_institutions.add(name)
|
||||
associated_institutions.append(name)
|
||||
|
||||
return cls(
|
||||
id=project.id or project.project_id,
|
||||
link=project.link,
|
||||
page_url=project.page_url,
|
||||
external_link=project.external_link,
|
||||
title_de=project.title_de,
|
||||
title_en=project.title_en,
|
||||
description_de=project.abstract_de,
|
||||
description_en=project.abstract_en,
|
||||
final_report_abstract_de=project.final_report_abstract_de,
|
||||
final_report_abstract_en=project.final_report_abstract_en,
|
||||
project_identifier_de=project.project_identifier_de,
|
||||
project_identifier_en=project.project_identifier_en,
|
||||
funding_start=project.funding_start,
|
||||
funding_end=project.funding_end,
|
||||
funding_period_de=project.funding_period_de,
|
||||
funding_period_en=project.funding_period_en,
|
||||
funding_type_de=project.funding_type_de,
|
||||
funding_type_en=project.funding_type_en,
|
||||
funding_type_key=project.funding_type_key,
|
||||
dfg_procedure=project.template_type,
|
||||
is_transfer_project=project.is_transfer_project,
|
||||
website_html_de=project.website_html_de,
|
||||
website_html_en=project.website_html_en,
|
||||
equipment_group=project.equipment_group,
|
||||
equipment_name=project.equipment_name,
|
||||
subject_area_de=project.subject_area_de,
|
||||
subject_area_en=project.subject_area_en,
|
||||
subject_classifications=subject_classifications,
|
||||
international_relation_de=project.international_relation_de,
|
||||
international_relation_en=project.international_relation_en,
|
||||
persons=persons,
|
||||
institutions=institutions,
|
||||
associated_persons=associated_persons,
|
||||
associated_institutions=associated_institutions,
|
||||
parent_project_id=project.parent_project_id,
|
||||
parent_title_de=project.parent_title_de,
|
||||
parent_title_en=project.parent_title_en,
|
||||
subprojects=subprojects,
|
||||
publications=publications,
|
||||
topics=project.topics,
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, obj: dict) -> "DfgProjectDetails":
|
||||
"""Convenience constructor from a raw dict (e.g. a JSON API response body)."""
|
||||
obj = cls._sanitize_raw_project_dict(obj)
|
||||
return cls.from_dfg_project(DFGProject.from_dict(obj))
|
||||
|
||||
@staticmethod
|
||||
def _sanitize_raw_project_dict(obj: dict) -> dict:
|
||||
"""
|
||||
Work around known mismatches between the generated DFGProject model
|
||||
and the actual shape of API/index data, before handing off to
|
||||
DFGProject.from_dict (which would otherwise raise a ValidationError
|
||||
and abort the whole parse).
|
||||
"""
|
||||
if isinstance(obj.get("subject_classifications"), list):
|
||||
obj = dict(obj)
|
||||
obj.pop("subject_classifications", None)
|
||||
return obj
|
||||
|
||||
@classmethod
|
||||
def from_elastic_hit(cls, hit: dict) -> "DfgProjectDetails":
|
||||
"""
|
||||
Create a DfgProject from an Elasticsearch hit, consolidating all
|
||||
person and institution fields into unified lists.
|
||||
Compatibility constructor for callers still reading from an
|
||||
Elasticsearch hit (e.g. `{"_id": ..., "_source": {...}}`), matching
|
||||
the old model's from_elastic_hit signature.
|
||||
"""
|
||||
source = dict(hit.get("_source", {}))
|
||||
|
||||
source = hit.get("_source", {})
|
||||
if source.get("id") is None and source.get("project_id") is None:
|
||||
raw_id = hit.get("_id")
|
||||
if raw_id is not None:
|
||||
try:
|
||||
source["id"] = int(raw_id)
|
||||
except (TypeError, ValueError):
|
||||
# Non-numeric _id (e.g. a composite/legacy key) - leave
|
||||
# id unset rather than fail the whole parse.
|
||||
pass
|
||||
|
||||
associated_persons: Set[str] = set()
|
||||
institutions: Set[str] = set()
|
||||
return cls.from_dict(source)
|
||||
|
||||
# --- Collect all persons and institutions from nested persons array ---
|
||||
persons_list = source.get("persons", [])
|
||||
if isinstance(persons_list, list):
|
||||
for p in persons_list:
|
||||
if isinstance(p, dict):
|
||||
full_name = p.get("full_name")
|
||||
if full_name:
|
||||
associated_persons.add(full_name.strip())
|
||||
|
||||
aff_de = p.get("affiliation_de")
|
||||
if aff_de:
|
||||
institutions.add(aff_de.strip())
|
||||
|
||||
aff_en = p.get("affiliation_en")
|
||||
if aff_en:
|
||||
institutions.add(aff_en.strip())
|
||||
|
||||
# --- Collect all persons from every person-related field ---
|
||||
|
||||
# Applicant fields
|
||||
_add_persons(source, associated_persons, "Antragsteller") # semicolon-separated
|
||||
_add_person(source, associated_persons, "Antragstellerin")
|
||||
_add_persons(
|
||||
source, associated_persons, "Antragstellerinnen"
|
||||
) # semicolon-separated
|
||||
_add_persons(
|
||||
source, associated_persons, "Antragstellerinnen / Antragsteller"
|
||||
) # semicolon-separated
|
||||
|
||||
# Co-applicant fields
|
||||
_add_persons(source, associated_persons, "Mitantragsteller")
|
||||
_add_person(source, associated_persons, "Mitantragstellerin")
|
||||
_add_persons(source, associated_persons, "Mitantragstellerinnen")
|
||||
_add_persons(
|
||||
source, associated_persons, "Mitantragstellerinnen / Mitantragsteller"
|
||||
)
|
||||
|
||||
# Former applicant fields
|
||||
_add_persons(source, associated_persons, "Ehemalige Antragsteller")
|
||||
_add_person(source, associated_persons, "Ehemalige Antragstellerin")
|
||||
_add_persons(source, associated_persons, "Ehemalige Antragstellerinnen")
|
||||
_add_persons(
|
||||
source,
|
||||
associated_persons,
|
||||
"Ehemalige Antragstellerinnen / Ehemalige Antragsteller",
|
||||
)
|
||||
_add_person(source, associated_persons, "Ehemaliger Antragsteller")
|
||||
|
||||
# Speaker / coordinator fields
|
||||
_add_person(source, associated_persons, "Sprecher")
|
||||
_add_person(source, associated_persons, "Sprecherin")
|
||||
_add_persons(source, associated_persons, "Sprecherinnen")
|
||||
_add_persons(source, associated_persons, "Sprecherinnen / Sprecher")
|
||||
_add_person(source, associated_persons, "Co-Sprecher")
|
||||
_add_persons(source, associated_persons, "Co-Sprecherinnen / Co-Sprecher")
|
||||
|
||||
# IGK partner speaker fields
|
||||
_add_person(source, associated_persons, "Sprecher (IGK-Partner)")
|
||||
_add_person(source, associated_persons, "Sprecherin (IGK-Partner)")
|
||||
_add_persons(
|
||||
source,
|
||||
associated_persons,
|
||||
"Sprecherinnen (IGK-Partner) / Sprecher (IGK-Partner)",
|
||||
)
|
||||
|
||||
# Leader fields
|
||||
_add_person(source, associated_persons, "Leiter")
|
||||
_add_person(source, associated_persons, "Leiterin")
|
||||
_add_persons(source, associated_persons, "Leiterinnen")
|
||||
_add_persons(source, associated_persons, "Leiterinnen / Leiter")
|
||||
|
||||
# Sub-project leader fields
|
||||
_add_persons(source, associated_persons, "Teilprojektleiter")
|
||||
_add_person(source, associated_persons, "Teilprojektleiterin")
|
||||
_add_persons(source, associated_persons, "Teilprojektleiterinnen")
|
||||
_add_persons(
|
||||
source, associated_persons, "Teilprojektleiterinnen / Teilprojektleiter"
|
||||
)
|
||||
|
||||
# Participating scientist fields
|
||||
_add_persons(source, associated_persons, "beteiligte Wissenschaftler")
|
||||
_add_person(source, associated_persons, "beteiligte Wissenschaftlerin")
|
||||
_add_persons(source, associated_persons, "beteiligte Wissenschaftlerinnen")
|
||||
_add_persons(
|
||||
source,
|
||||
associated_persons,
|
||||
"beteiligte Wissenschaftlerinnen / beteiligte Wissenschaftler",
|
||||
)
|
||||
_add_person(source, associated_persons, "beteiligter Wissenschaftler")
|
||||
|
||||
# Participating person fields
|
||||
_add_person(source, associated_persons, "Beteiligte Person")
|
||||
_add_persons(source, associated_persons, "Beteiligte Personen")
|
||||
|
||||
# Host fields (for guest researchers)
|
||||
_add_person(source, associated_persons, "Gastgeber")
|
||||
_add_person(source, associated_persons, "Gastgeberin")
|
||||
_add_persons(source, associated_persons, "Gastgeberinnen")
|
||||
_add_persons(source, associated_persons, "Gastgeberinnen / Gastgeber")
|
||||
|
||||
# Cooperation partner fields
|
||||
_add_person(source, associated_persons, "Kooperationspartner")
|
||||
_add_person(source, associated_persons, "Kooperationspartnerin")
|
||||
_add_persons(source, associated_persons, "Kooperationspartnerinnen")
|
||||
_add_persons(
|
||||
source, associated_persons, "Kooperationspartnerinnen / Kooperationspartner"
|
||||
)
|
||||
|
||||
# Co-responsible fields
|
||||
_add_person(source, associated_persons, "Mitverantwortlich")
|
||||
_add_person(source, associated_persons, "Mitverantwortlich(e)")
|
||||
_add_persons(source, associated_persons, "Mitverantwortliche")
|
||||
|
||||
# Application partner
|
||||
_add_person(source, associated_persons, "Anwendungspartner")
|
||||
|
||||
# Foreign co-applicant fields
|
||||
_add_persons(source, associated_persons, "ausländische Mitantragsteller")
|
||||
_add_person(source, associated_persons, "ausländischer Mitantragsteller")
|
||||
|
||||
# Person creator (from nested fields)
|
||||
if "person_creater_name" in source and source["person_creater_name"]:
|
||||
associated_persons.add(source["person_creater_name"].strip())
|
||||
|
||||
# Deputy (stellvertr) - nested object
|
||||
stellvertr = source.get("stellvertr")
|
||||
if stellvertr and isinstance(stellvertr, dict):
|
||||
for field in ["stellvertreter", "stellvertreterin"]:
|
||||
if field in stellvertr and stellvertr[field]:
|
||||
associated_persons.add(stellvertr[field].strip())
|
||||
|
||||
# --- Collect all institutions ---
|
||||
|
||||
_add_institution(source, institutions, "Antragstellende Institution")
|
||||
_add_institution(source, institutions, "Mitantragstellende Institution")
|
||||
_add_institution(source, institutions, "Beteiligte Einrichtung")
|
||||
_add_institution(source, institutions, "Beteiligte Hochschule")
|
||||
_add_institution(source, institutions, "Beteiligte Institution")
|
||||
_add_institution(source, institutions, "IGK-Partnerinstitution")
|
||||
_add_institution(source, institutions, "Partnerorganisation")
|
||||
_add_institution(source, institutions, "Unternehmen")
|
||||
|
||||
# Foreign institution (nested object)
|
||||
auslaend = source.get("ausländ")
|
||||
if auslaend and isinstance(auslaend, dict):
|
||||
for field in [
|
||||
"auslaendischeInstitution",
|
||||
"auslaendischeInstitution2",
|
||||
"auslaendischesUnternehmen",
|
||||
"auslaendischesUnternehmen2",
|
||||
]:
|
||||
if field in auslaend and auslaend[field]:
|
||||
institutions.add(auslaend[field].strip())
|
||||
|
||||
return cls(
|
||||
id=hit["_id"],
|
||||
link=source.get("link") or source.get("page_url"),
|
||||
title=source.get("title") or source.get("title_de") or source.get("title_en"),
|
||||
description=source.get("description") or source.get("abstract_de") or source.get("abstract_en"),
|
||||
project_identifier=source.get("Projektkennung") or source.get("project_identifier_de") or source.get("project_identifier_en"),
|
||||
funding_start_date=str(source.get("funding_start")) if source.get("funding_start") is not None else None,
|
||||
funding_end_date=str(source.get("funding_end")) if source.get("funding_end") is not None else None,
|
||||
dfg_procedure=source.get("DFG-Verfahren") or source.get("template_type"),
|
||||
subject_area=source.get("Fachliche Zuordnung") or source.get("subject_area_de") or source.get("subject_area_en"),
|
||||
funding_type=source.get("Förderung") or source.get("funding_type_sort"),
|
||||
international_reference=source.get("Internationaler Bezug") or source.get("international_relation_de") or source.get("international_relation_en"),
|
||||
website=source.get("Webseite"),
|
||||
associated_persons=sorted(associated_persons), # sorted for consistency
|
||||
institutions=sorted(institutions),
|
||||
subproject_of=source.get("Teilprojekt zu") or source.get("parent_project_id"),
|
||||
)
|
||||
|
||||
|
||||
# --- Helper functions for parsing source fields ---
|
||||
|
||||
def _add_person(source: dict, persons: Set[str], field: str) -> None:
|
||||
"""Add a single person value from a field."""
|
||||
if field in source and source[field]:
|
||||
value = source[field].strip()
|
||||
if value:
|
||||
persons.add(value)
|
||||
|
||||
|
||||
def _add_persons(source: dict, persons: Set[str], field: str) -> None:
|
||||
"""Add persons from a semicolon-separated field."""
|
||||
if field in source and source[field]:
|
||||
for person in source[field].split(";"):
|
||||
cleaned = person.strip()
|
||||
if cleaned:
|
||||
persons.add(cleaned)
|
||||
|
||||
|
||||
def _add_institution(source: dict, institutions: Set[str], field: str) -> None:
|
||||
"""Add a single institution value from a field."""
|
||||
if field in source and source[field]:
|
||||
value = source[field].strip()
|
||||
if value:
|
||||
institutions.add(value)
|
||||
def enrich_orcids(self, persons_by_id: dict) -> None:
|
||||
"""
|
||||
Fill in orcid_id on each entry in `self.persons`, given a mapping of
|
||||
person_id -> DFGPersonPerson (or DFGPerson) for the persons involved
|
||||
in this project
|
||||
"""
|
||||
for person in self.persons:
|
||||
record = persons_by_id.get(person.person_id)
|
||||
if record is not None:
|
||||
person.orcid_id = getattr(record, "orcid_id", None)
|
||||
@@ -29,6 +29,7 @@ from inse.models.projects_dfg_v2.project.dfg_project_subprojects_inner import DF
|
||||
from typing import Optional, Set
|
||||
from typing_extensions import Self
|
||||
from pydantic_core import to_jsonable_python
|
||||
from inse.models.openalex.topic import Topic, TopicDomain, TopicField, TopicSubfield
|
||||
|
||||
class DFGProject(BaseModel):
|
||||
"""
|
||||
@@ -52,7 +53,7 @@ class DFGProject(BaseModel):
|
||||
funding_type_key: Optional[StrictStr] = None
|
||||
funding_type_sort: Optional[StrictStr] = None
|
||||
id: Optional[StrictInt] = None
|
||||
institution_roles_order: Optional[StrictStr] = None
|
||||
institution_roles_order: Optional[list[StrictStr]] = None
|
||||
institutions: Optional[List[DFGProjectInstitutionsInner]] = None
|
||||
international_relation_de: Optional[StrictStr] = None
|
||||
international_relation_en: Optional[StrictStr] = None
|
||||
@@ -62,7 +63,7 @@ class DFGProject(BaseModel):
|
||||
parent_project_id: Optional[StrictInt] = None
|
||||
parent_title_de: Optional[StrictStr] = None
|
||||
parent_title_en: Optional[StrictStr] = None
|
||||
person_roles_order: Optional[StrictStr] = None
|
||||
person_roles_order: Optional[list[StrictStr]] = None
|
||||
persons: Optional[List[DFGProjectPersonsInner]] = None
|
||||
project: Optional[DFGProjectProject] = None
|
||||
project_id: Optional[StrictInt] = None
|
||||
@@ -72,13 +73,14 @@ class DFGProject(BaseModel):
|
||||
subject_area_de: Optional[StrictStr] = None
|
||||
subject_area_en: Optional[StrictStr] = None
|
||||
subject_classifications: Optional[DFGProjectFachgebieteInner] = None
|
||||
subproject_order: Optional[StrictStr] = None
|
||||
subproject_order: Optional[list[StrictStr]] = None
|
||||
subprojects: Optional[List[DFGProjectSubprojectsInner]] = None
|
||||
template_type: Optional[StrictStr] = None
|
||||
title_de: Optional[StrictStr] = None
|
||||
title_en: Optional[StrictStr] = None
|
||||
website_html_de: Optional[StrictStr] = None
|
||||
website_html_en: Optional[StrictStr] = None
|
||||
topics: Optional[List[Topic]] = None
|
||||
__properties: ClassVar[List[str]] = ["abstract_de", "abstract_en", "equipment_group", "equipment_name", "external_link", "fachgebiete", "fetched_at", "final_report_abstract_de", "final_report_abstract_en", "funding_end", "funding_period_de", "funding_period_en", "funding_start", "funding_type_de", "funding_type_en", "funding_type_key", "funding_type_sort", "id", "institution_roles_order", "institutions", "international_relation_de", "international_relation_en", "is_transfer_project", "link", "page_url", "parent_project_id", "parent_title_de", "parent_title_en", "person_roles_order", "persons", "project", "project_id", "project_identifier_de", "project_identifier_en", "publications", "subject_area_de", "subject_area_en", "subject_classifications", "subproject_order", "subprojects", "template_type", "title_de", "title_en", "website_html_de", "website_html_en"]
|
||||
|
||||
model_config = ConfigDict(
|
||||
@@ -168,9 +170,18 @@ class DFGProject(BaseModel):
|
||||
"""Create an instance of DFGProject from a dict"""
|
||||
if obj is None:
|
||||
return None
|
||||
|
||||
|
||||
topics_raw = obj.get("topics") or []
|
||||
if not isinstance(obj, dict):
|
||||
return cls.model_validate(obj)
|
||||
topics = None
|
||||
if isinstance(topics_raw, list) and topics_raw:
|
||||
|
||||
sorted_topics_raw = sorted(
|
||||
(t for t in topics_raw if isinstance(t, dict)),
|
||||
key=lambda t: t.get("rank") if t.get("rank") is not None else float("inf"),
|
||||
)
|
||||
topics = [cls._topic_from_match(t) for t in sorted_topics_raw]
|
||||
|
||||
_obj = cls.model_validate({
|
||||
"abstract_de": obj.get("abstract_de"),
|
||||
@@ -217,8 +228,29 @@ class DFGProject(BaseModel):
|
||||
"title_de": obj.get("title_de"),
|
||||
"title_en": obj.get("title_en"),
|
||||
"website_html_de": obj.get("website_html_de"),
|
||||
"website_html_en": obj.get("website_html_en")
|
||||
"website_html_en": obj.get("website_html_en"),
|
||||
"topics": topics,
|
||||
})
|
||||
return _obj
|
||||
|
||||
@staticmethod
|
||||
def _topic_from_match(match: Dict[str, Any]) -> Topic:
|
||||
"""Builds a Topic model from a flattened topic_match dict.
|
||||
"""
|
||||
domain_name = match.get("domain")
|
||||
field_name = match.get("field")
|
||||
subfield_name = match.get("subfield")
|
||||
|
||||
domain = TopicDomain(display_name=domain_name) if domain_name else None
|
||||
field = TopicField(display_name=field_name) if field_name else None
|
||||
subfield = TopicSubfield(display_name=subfield_name) if subfield_name else None
|
||||
|
||||
return Topic(
|
||||
id=match.get("topic_id"),
|
||||
display_name=match.get("topic_display_name"),
|
||||
domain=domain,
|
||||
field=field,
|
||||
subfield=subfield,
|
||||
)
|
||||
|
||||
|
||||
|
||||
@@ -25,7 +25,8 @@ from inse.models.projects_eu_cordis.fp7.fp7_topic import Fp7Topic
|
||||
from inse.models.projects_eu_cordis.fp7.fp7_web_link import Fp7WebLink
|
||||
from inse.models.projects_eu_cordis.fp7.fp7_eurosci_voc import Fp7EurosciVoc
|
||||
from inse.models.projects_eu_cordis.fp7.fp7_legal_basis import Fp7LegalBasis
|
||||
|
||||
from inse.authors.v2.model import AuthorPage
|
||||
from inse.models.openalex.topic import Topic
|
||||
|
||||
class Fp7ProjectDetails(BaseModel):
|
||||
"""
|
||||
@@ -70,6 +71,9 @@ class Fp7ProjectDetails(BaseModel):
|
||||
organization_count: Optional[int] = Field(default=None, alias="organizationCount")
|
||||
publication_count: Optional[int] = Field(default=None, alias="publicationCount")
|
||||
ipr_count: Optional[int] = Field(default=None, alias="iprCount")
|
||||
# OpenAlex related fields
|
||||
oa_topics: Optional[List[Topic]] = Field(default=None, alias="oaTopics", description="OpenAlex topics associated with the project")
|
||||
oa_authors: Optional[AuthorPage] = Field(default=None, alias="oaAuthors", description="OpenAlex authors associated with the project")
|
||||
|
||||
__properties: ClassVar[List[str]] = [
|
||||
"acronym", "contentUpdateDate", "ecMaxContribution", "ecSignatureDate",
|
||||
@@ -79,7 +83,7 @@ class Fp7ProjectDetails(BaseModel):
|
||||
"title", "topics", "totalCost",
|
||||
"organizations", "publications", "iprs", "reportSummaries",
|
||||
"topicsList", "webLinks", "eurosciVoc", "legalBasisList",
|
||||
"organizationCount", "publicationCount", "iprCount"
|
||||
"organizationCount", "publicationCount", "iprCount","oaTopics", "oaAuthors"
|
||||
]
|
||||
|
||||
model_config = ConfigDict(
|
||||
@@ -163,6 +167,10 @@ class Fp7ProjectDetails(BaseModel):
|
||||
"organizationCount": len(obj.get("organizations", [])) if obj.get("organizations") else 0,
|
||||
"publicationCount": len(obj.get("publications", [])) if obj.get("publications") else 0,
|
||||
"iprCount": len(obj.get("iprs", [])) if obj.get("iprs") else 0,
|
||||
|
||||
# # OpenAlex related fields
|
||||
# "oaTopics": [Topic.from_dict(topic) for topic in obj.get("oaTopics", [])] if obj.get("oaTopics") else None,
|
||||
# "oaAuthors": AuthorPage.from_dict(obj.get("oaAuthors")) if obj.get("oaAuthors") else None,
|
||||
})
|
||||
return _obj
|
||||
|
||||
@@ -178,6 +186,8 @@ class Fp7ProjectDetails(BaseModel):
|
||||
web_links: Optional[List[Fp7WebLink]] = None,
|
||||
eurosci_voc: Optional[List[Fp7EurosciVoc]] = None,
|
||||
legal_basis_list: Optional[List[Fp7LegalBasis]] = None,
|
||||
oa_topics: Optional[List[Topic]] = None,
|
||||
oa_authors: Optional[AuthorPage] = None,
|
||||
) -> Self:
|
||||
"""
|
||||
Factory method to create a detailed project from a base project and its relations.
|
||||
@@ -211,4 +221,6 @@ class Fp7ProjectDetails(BaseModel):
|
||||
organizationCount=len(organizations) if organizations else 0,
|
||||
publicationCount=len(publications) if publications else 0,
|
||||
iprCount=len(iprs) if iprs else 0,
|
||||
oa_authors=oa_authors,
|
||||
oa_topics=oa_topics or [],
|
||||
)
|
||||
+11
-2
@@ -26,7 +26,8 @@ from inse.models.projects_eu_cordis.horizon2020.h2020_web_link import H2020WebLi
|
||||
from inse.models.projects_eu_cordis.horizon2020.h2020_eurosci_voc import H2020EurosciVoc
|
||||
from inse.models.projects_eu_cordis.horizon2020.h2020_legal_basis import H2020LegalBasis
|
||||
from inse.models.projects_eu_cordis.horizon2020.h2020_erc_pi import H2020ErcPI
|
||||
|
||||
from inse.authors.v2.model import AuthorPage
|
||||
from inse.models.openalex.topic import Topic
|
||||
|
||||
class H2020ProjectDetails(BaseModel):
|
||||
"""
|
||||
@@ -73,7 +74,10 @@ class H2020ProjectDetails(BaseModel):
|
||||
publication_count: Optional[int] = Field(default=None, alias="publicationCount")
|
||||
deliverable_count: Optional[int] = Field(default=None, alias="deliverableCount")
|
||||
erc_pi_count: Optional[int] = Field(default=None, alias="ercPiCount")
|
||||
|
||||
# OpenAlex related fields
|
||||
oa_topics: Optional[List[Topic]] = Field(default=None, alias="oaTopics", description="OpenAlex topics associated with the project")
|
||||
oa_authors: Optional[AuthorPage] = Field(default=None, alias="oaAuthors", description="OpenAlex authors associated with the project")
|
||||
|
||||
__properties: ClassVar[List[str]] = [
|
||||
"acronym", "contentUpdateDate", "ecMaxContribution", "ecSignatureDate",
|
||||
"endDate", "frameworkProgramme", "fundingScheme", "grantDoi",
|
||||
@@ -84,6 +88,7 @@ class H2020ProjectDetails(BaseModel):
|
||||
"topicsList", "webLinks", "eurosciVoc", "legalBasisList",
|
||||
"ercPrincipalInvestigators",
|
||||
"organizationCount", "publicationCount", "deliverableCount", "ercPiCount"
|
||||
,"oaTopics", "oaAuthors"
|
||||
]
|
||||
|
||||
model_config = ConfigDict(
|
||||
@@ -185,6 +190,8 @@ class H2020ProjectDetails(BaseModel):
|
||||
eurosci_voc: Optional[List[H2020EurosciVoc]] = None,
|
||||
legal_basis_list: Optional[List[H2020LegalBasis]] = None,
|
||||
erc_principal_investigators: Optional[List[H2020ErcPI]] = None,
|
||||
oa_topics: Optional[List[Topic]] = None,
|
||||
oa_authors: Optional[AuthorPage] = None,
|
||||
) -> Self:
|
||||
"""
|
||||
Factory method to create a detailed project from a base project and its relations.
|
||||
@@ -221,4 +228,6 @@ class H2020ProjectDetails(BaseModel):
|
||||
publicationCount=len(publications) if publications else 0,
|
||||
deliverableCount=len(deliverables) if deliverables else 0,
|
||||
ercPiCount=len(erc_principal_investigators) if erc_principal_investigators else 0,
|
||||
oa_authors=oa_authors,
|
||||
oa_topics=oa_topics or [],
|
||||
)
|
||||
+10
-3
@@ -25,7 +25,8 @@ from inse.models.projects_eu_cordis.horizon_europe.heu_topic import HEUTopic
|
||||
from inse.models.projects_eu_cordis.horizon_europe.heu_web_link import HEUWebLink
|
||||
from inse.models.projects_eu_cordis.horizon_europe.heu_eurosci_voc import HEUEurosciVoc
|
||||
from inse.models.projects_eu_cordis.horizon_europe.heu_legal_basis import HEULegalBasis
|
||||
|
||||
from inse.authors.v2.model import AuthorPage
|
||||
from inse.models.openalex.topic import Topic
|
||||
|
||||
class HEUProjectDetails(BaseModel):
|
||||
"""
|
||||
@@ -70,7 +71,9 @@ class HEUProjectDetails(BaseModel):
|
||||
organization_count: Optional[int] = Field(default=None, alias="organizationCount")
|
||||
publication_count: Optional[int] = Field(default=None, alias="publicationCount")
|
||||
deliverable_count: Optional[int] = Field(default=None, alias="deliverableCount")
|
||||
|
||||
# OpenAlex related fields
|
||||
oa_topics: Optional[List[Topic]] = Field(default=None, alias="oaTopics", description="OpenAlex topics associated with the project")
|
||||
oa_authors: Optional[AuthorPage] = Field(default=None, alias="oaAuthors", description="OpenAlex authors associated with the project")
|
||||
__properties: ClassVar[List[str]] = [
|
||||
"acronym", "contentUpdateDate", "ecMaxContribution", "ecSignatureDate",
|
||||
"endDate", "frameworkProgramme", "fundingScheme", "grantDoi",
|
||||
@@ -79,7 +82,7 @@ class HEUProjectDetails(BaseModel):
|
||||
"title", "topics", "totalCost",
|
||||
"organizations", "publications", "deliverables", "reportSummaries",
|
||||
"topicsList", "webLinks", "eurosciVoc", "legalBasisList",
|
||||
"organizationCount", "publicationCount", "deliverableCount"
|
||||
"organizationCount", "publicationCount", "deliverableCount","oaTopics", "oaAuthors"
|
||||
]
|
||||
|
||||
model_config = ConfigDict(
|
||||
@@ -178,6 +181,8 @@ class HEUProjectDetails(BaseModel):
|
||||
web_links: Optional[List[HEUWebLink]] = None,
|
||||
eurosci_voc: Optional[List[HEUEurosciVoc]] = None,
|
||||
legal_basis_list: Optional[List[HEULegalBasis]] = None,
|
||||
oa_topics: Optional[List[Topic]] = None,
|
||||
oa_authors: Optional[AuthorPage] = None,
|
||||
) -> Self:
|
||||
"""
|
||||
Factory method to create a detailed project from a base project and its relations.
|
||||
@@ -211,4 +216,6 @@ class HEUProjectDetails(BaseModel):
|
||||
organizationCount=len(organizations) if organizations else 0,
|
||||
publicationCount=len(publications) if publications else 0,
|
||||
deliverableCount=len(deliverables) if deliverables else 0,
|
||||
oa_authors=oa_authors,
|
||||
oa_topics=oa_topics or [],
|
||||
)
|
||||
@@ -256,6 +256,8 @@ class OrgPatentsSearchClient:
|
||||
page: int = 0,
|
||||
size: int = DEFAULT_PAGE_SIZE,
|
||||
source: str | None = None,
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> tuple[list[OrgPatentEntry], int]:
|
||||
short_id = institution_id.replace("https://openalex.org/", "").upper()
|
||||
filters: list[dict[str, Any]] = [{"term": {"institution_id": short_id}}]
|
||||
@@ -270,6 +272,14 @@ class OrgPatentsSearchClient:
|
||||
if source in ("EPO", "USPTO"):
|
||||
filters.append({"term": {"source": source}})
|
||||
|
||||
year_range: dict[str, int] = {}
|
||||
if from_year is not None:
|
||||
year_range["gte"] = from_year
|
||||
if to_year is not None:
|
||||
year_range["lte"] = to_year
|
||||
if year_range:
|
||||
filters.append({"range": {"publication_year": year_range}})
|
||||
|
||||
payload = {
|
||||
"from": page * size,
|
||||
"size": size,
|
||||
@@ -304,11 +314,27 @@ class OrgPatentsSearchClient:
|
||||
self,
|
||||
institution_id: str,
|
||||
size: int = 10,
|
||||
from_year: int | None = None,
|
||||
to_year: int | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
short_id = institution_id.replace("https://openalex.org/", "").upper()
|
||||
filters: list[dict[str, Any]] = [{"term": {"institution_id": short_id}}]
|
||||
year_range: dict[str, int] = {}
|
||||
if from_year is not None:
|
||||
year_range["gte"] = from_year
|
||||
if to_year is not None:
|
||||
year_range["lte"] = to_year
|
||||
if year_range:
|
||||
filters.append({"range": {"publication_year": year_range}})
|
||||
|
||||
query = (
|
||||
{"term": {"institution_id": short_id}}
|
||||
if len(filters) == 1
|
||||
else {"bool": {"filter": filters}}
|
||||
)
|
||||
payload = {
|
||||
"size": 0,
|
||||
"query": {"term": {"institution_id": short_id}},
|
||||
"query": query,
|
||||
"aggs": {
|
||||
"matched_authors_nested": {
|
||||
"nested": {"path": "matched_authors"},
|
||||
|
||||
@@ -53,3 +53,43 @@ async def test_top_authors_by_institution_aggregates_matched_authors():
|
||||
payload["aggs"]["matched_authors_nested"]["nested"]["path"]
|
||||
== "matched_authors"
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_top_authors_by_institution_filters_by_publication_year():
|
||||
requests: list[httpx.Request] = []
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
requests.append(request)
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"aggregations": {
|
||||
"matched_authors_nested": {
|
||||
"authors": {"buckets": []}
|
||||
}
|
||||
}
|
||||
},
|
||||
)
|
||||
|
||||
client = OrgPatentsSearchClient(
|
||||
base_url="https://example.test",
|
||||
api_key="key",
|
||||
transport=httpx.MockTransport(handler),
|
||||
)
|
||||
|
||||
await client.top_authors_by_institution(
|
||||
"https://openalex.org/I123",
|
||||
from_year=2020,
|
||||
to_year=2024,
|
||||
)
|
||||
|
||||
payload = json.loads(requests[0].content)
|
||||
assert payload["query"] == {
|
||||
"bool": {
|
||||
"filter": [
|
||||
{"term": {"institution_id": "I123"}},
|
||||
{"range": {"publication_year": {"gte": 2020, "lte": 2024}}},
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
from typing import Optional
|
||||
|
||||
from inse.model import Page
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class BundInstitutionSummary(BaseModel):
|
||||
"""A single institution entry derived from a BUND project record.
|
||||
|
||||
Note: this index has no dedicated institution entity — each entry is
|
||||
reconstructed from the agency/recipient fields on a single project hit,
|
||||
so the same institution may appear multiple times (once per project).
|
||||
"""
|
||||
|
||||
department: Optional[str] = None
|
||||
department_fullname: Optional[str] = None
|
||||
name: Optional[str] = None
|
||||
recepient: Optional[str] = None
|
||||
municipality: Optional[str] = None
|
||||
place: Optional[str] = None
|
||||
state: Optional[str] = None
|
||||
country: Optional[str] = None
|
||||
|
||||
@classmethod
|
||||
def from_source(cls, source: dict) -> "BundInstitutionSummary":
|
||||
"""Build a BundInstitutionSummary from a raw Elasticsearch _source dict."""
|
||||
return cls(
|
||||
department=source.get("Ressort"),
|
||||
department_fullname=source.get("Ressort_fullname"),
|
||||
name=source.get("Ausführende Stelle"),
|
||||
recepient=source.get("Zuwendungsempfänger"),
|
||||
municipality=source.get("Stadt/Gemeinde"),
|
||||
place=source.get("Ort"),
|
||||
state=source.get("Bundesland"),
|
||||
country=source.get("Staat"),
|
||||
)
|
||||
|
||||
|
||||
class BundInstitutionSummaryPage(Page[BundInstitutionSummary]):
|
||||
"""A paginated response containing a list of institutions."""
|
||||
|
||||
pass
|
||||
@@ -0,0 +1,47 @@
|
||||
import logging
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, Query
|
||||
|
||||
from inse.projects.bund_institutions.model import BundInstitutionSummaryPage
|
||||
from inse.tags import Tags
|
||||
from inse.projects.bund_institutions.service import autocomplete_institutions_for_selector, get_institutions_by_names
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
INSTITUTIONS_BUND_PREFIX = "/api/bund/institutions"
|
||||
|
||||
router = APIRouter(prefix=INSTITUTIONS_BUND_PREFIX, tags=[Tags.BUND_INSTITUTIONS])
|
||||
|
||||
|
||||
@router.get(
|
||||
"/names",
|
||||
operation_id="getBundInstitutionsByName",
|
||||
summary="Returns a list of institutions based on their names.",
|
||||
)
|
||||
async def get_bund_institutions(
|
||||
institution_names: Annotated[
|
||||
list[str],
|
||||
Query(description="A list of institution names to retrieve."),
|
||||
] = [],
|
||||
) -> BundInstitutionSummaryPage:
|
||||
|
||||
return await get_institutions_by_names(institution_names=institution_names or [])
|
||||
|
||||
|
||||
@router.get(
|
||||
"/autocomplete/selector",
|
||||
operation_id="getBundInstitutionAutocompleteForSelector",
|
||||
summary="Returns a list of institutions based on a search term for autocomplete functionality.",
|
||||
)
|
||||
async def get_bund_institution_autocomplete(
|
||||
query: Annotated[
|
||||
str,
|
||||
Query(
|
||||
description="A search term to filter institutions by (partial matches allowed)."
|
||||
),
|
||||
] = "",
|
||||
) -> BundInstitutionSummaryPage:
|
||||
|
||||
return await autocomplete_institutions_for_selector(query=query)
|
||||
@@ -0,0 +1,169 @@
|
||||
import logging
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESIndex, ESCluster
|
||||
|
||||
from inse.projects.bund_institutions.model import BundInstitutionSummary
|
||||
from inse.projects.bund_institutions.model import BundInstitutionSummaryPage
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Fields on the BUND project index that describe the institution/agency involved,
|
||||
# used consistently across all lookup functions below.
|
||||
_INSTITUTION_SOURCE_FIELDS = [
|
||||
"Ressort",
|
||||
"Ressort_fullname",
|
||||
"Ausführende Stelle",
|
||||
"Zuwendungsempfänger",
|
||||
"Stadt/Gemeinde",
|
||||
"Ort",
|
||||
"Bundesland",
|
||||
"Staat",
|
||||
]
|
||||
|
||||
|
||||
async def search_institutions(
|
||||
page: int = 0,
|
||||
size: int = 10,
|
||||
query: Optional[Dict] = None,
|
||||
source: Optional[List[str]] = None,
|
||||
sort: Optional[List[Dict]] = None,
|
||||
body: Optional[Dict] = None,
|
||||
) -> BundInstitutionSummaryPage:
|
||||
"""Searches for institutions in the BUND Projects Elasticsearch index based on the provided parameters.
|
||||
|
||||
Note: PROJECTS_BUND_V1 indexes projects, not institutions directly, so each
|
||||
matching project hit is reshaped into a BundInstitutionSummary. The same
|
||||
institution may therefore appear multiple times if it's tied to multiple projects.
|
||||
|
||||
Args:
|
||||
page (int, optional): The page number to retrieve. Defaults to 0.
|
||||
size (int, optional): The number of institutions to retrieve per page. Defaults to 10.
|
||||
query (Optional[Dict], optional): The search query to filter institutions by. Defaults to None.
|
||||
source (Optional[List[str]], optional): A list of fields to include in the response. Defaults to None.
|
||||
sort (Optional[List[Dict]], optional): A list of sorting criteria. Defaults to None.
|
||||
body (Optional[Dict], optional): The request body for the Elasticsearch search query. Defaults to None.
|
||||
|
||||
Returns:
|
||||
BundInstitutionSummaryPage: A page of institutions matching the search criteria.
|
||||
"""
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.PROJECTS_BUND_V1,
|
||||
cluster=ESCluster.INSE,
|
||||
query=query,
|
||||
source=source or _INSTITUTION_SOURCE_FIELDS,
|
||||
size=size,
|
||||
offset=size * page,
|
||||
sort=sort,
|
||||
body=body,
|
||||
)
|
||||
|
||||
hits_block = response.get("hits", {})
|
||||
hits = hits_block.get("hits", [])
|
||||
institutions: List[BundInstitutionSummary] = [
|
||||
BundInstitutionSummary.from_source(hit.get("_source", {})) for hit in hits
|
||||
]
|
||||
|
||||
return BundInstitutionSummaryPage(
|
||||
elements=institutions,
|
||||
total=hits_block.get("total", {}).get("value", len(institutions)),
|
||||
page=page,
|
||||
size=size,
|
||||
)
|
||||
|
||||
|
||||
async def get_institutions_by_names(institution_names: List[str]) -> BundInstitutionSummaryPage:
|
||||
"""Retrieves institutions based on a list of institution (Ausführende Stelle) names.
|
||||
|
||||
Args:
|
||||
institution_names (List[str]): A list of institution names to retrieve.
|
||||
|
||||
Returns:
|
||||
BundInstitutionSummaryPage: A page of institutions matching the provided names.
|
||||
"""
|
||||
logger.debug(f"Fetching institutions for names: {institution_names}")
|
||||
if not institution_names:
|
||||
return BundInstitutionSummaryPage(elements=[], total=0, page=0, size=0)
|
||||
|
||||
return await search_institutions(
|
||||
page=0,
|
||||
size=len(institution_names),
|
||||
query={
|
||||
"terms": {
|
||||
"Ausführende Stelle.keyword": institution_names,
|
||||
}
|
||||
},
|
||||
source=_INSTITUTION_SOURCE_FIELDS,
|
||||
)
|
||||
|
||||
|
||||
async def autocomplete_institutions(
|
||||
query: str, page: int = 0, size: int = 10, source: Optional[List[str]] = None
|
||||
) -> BundInstitutionSummaryPage:
|
||||
"""Autocompletes institutions based on a search term, matching against both the
|
||||
executing agency (Ausführende Stelle) and recipient (Zuwendungsempfänger) fields.
|
||||
|
||||
Args:
|
||||
query (str): The search term to autocomplete institutions with.
|
||||
page (int, optional): The page number to retrieve. Defaults to 0.
|
||||
size (int, optional): The number of institutions to retrieve per page. Defaults to 10.
|
||||
source (Optional[List[str]], optional): A list of fields to include in the response. Defaults to None.
|
||||
|
||||
Returns:
|
||||
BundInstitutionSummaryPage: A page of institutions matching the autocomplete criteria.
|
||||
"""
|
||||
logger.debug(f"Autocomplete institutions for query: {query}")
|
||||
if not query:
|
||||
return BundInstitutionSummaryPage(elements=[], total=0, page=0, size=0)
|
||||
|
||||
return await search_institutions(
|
||||
page=page,
|
||||
size=size,
|
||||
query={
|
||||
"bool": {
|
||||
"should": [
|
||||
{
|
||||
"match_phrase_prefix": {
|
||||
"Ausführende Stelle": {
|
||||
"query": query,
|
||||
"max_expansions": 50,
|
||||
"boost": 2,
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"match_phrase_prefix": {
|
||||
"Zuwendungsempfänger": {
|
||||
"query": query,
|
||||
"max_expansions": 50,
|
||||
}
|
||||
}
|
||||
},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
},
|
||||
source=source or _INSTITUTION_SOURCE_FIELDS,
|
||||
)
|
||||
|
||||
|
||||
async def autocomplete_institutions_for_selector(
|
||||
query: str, page: int = 0, size: int = 10
|
||||
) -> BundInstitutionSummaryPage:
|
||||
"""Autocompletes institutions based on a search term for use in a selector component.
|
||||
|
||||
Args:
|
||||
query (str): The search term to filter institutions by (partial matches allowed).
|
||||
page (int, optional): The page number to retrieve. Defaults to 0.
|
||||
size (int, optional): The number of institutions to retrieve per page. Defaults to 10.
|
||||
|
||||
Returns:
|
||||
BundInstitutionSummaryPage: A page of institutions matching the autocomplete criteria.
|
||||
"""
|
||||
return await autocomplete_institutions(
|
||||
query=query,
|
||||
page=page,
|
||||
size=size,
|
||||
source=_INSTITUTION_SOURCE_FIELDS,
|
||||
)
|
||||
@@ -46,7 +46,7 @@ from inse.models.projects_eu_cordis.horizon_europe.heu_web_link import HEUWebLin
|
||||
from inse.models.projects_eu_cordis.horizon_europe.heu_eurosci_voc import HEUEurosciVoc
|
||||
from inse.models.projects_eu_cordis.horizon_europe.heu_legal_basis import HEULegalBasis
|
||||
from inse.models.projects_eu_cordis.horizon_europe.heu_project_details import HEUProjectDetails
|
||||
|
||||
from inse.projects.model import EuCordisProjectType, EuCordisProjectSummary
|
||||
from inse.projects.model import (
|
||||
EuCordisProjectType,
|
||||
EuCordisProjectSearchPage,
|
||||
@@ -56,7 +56,7 @@ from inse.projects.model import (
|
||||
EuCordisEurosciVocSummary,
|
||||
)
|
||||
from inse.projects.logic import get_eu_project_ids_by_openalex_topic_ids, get_openalex_topics_for_eu_projects
|
||||
|
||||
from inse.models.openalex.topic import Topic
|
||||
|
||||
settings = get_settings()
|
||||
logger = logging.getLogger(__name__)
|
||||
@@ -96,24 +96,13 @@ _HEU_ENTITY_CONFIGS = [
|
||||
{"key": "eurosci_voc", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_EUROSCIVOC, "model_class": HEUEurosciVoc},
|
||||
{"key": "legal_basis_list", "index_pattern": ESIndex.CORDIS_EU_HORIZON_EUROPE_LEGAL_BASIS, "model_class": HEULegalBasis},
|
||||
]
|
||||
|
||||
async def get_enriched_cordis_project_by_id(
|
||||
project_id: str,
|
||||
) -> Optional[Union[Fp7ProjectDetails, H2020ProjectDetails, HEUProjectDetails]]:
|
||||
"""
|
||||
Fetches and enriches a single Cordis EU project by its ID across all programme types.
|
||||
|
||||
Args:
|
||||
project_id: The project ID to fetch.
|
||||
|
||||
Returns:
|
||||
The enriched detailed project model, or None if not found.
|
||||
"""
|
||||
if not project_id:
|
||||
return None
|
||||
|
||||
query = {"bool": {"filter": [{"term": {"id": project_id}}]}}
|
||||
|
||||
response = await elasticsearch.search(
|
||||
query=query,
|
||||
index=ESIndex.CORDIS_EU_PROJECTS_WILDCARD,
|
||||
@@ -130,33 +119,46 @@ async def get_enriched_cordis_project_by_id(
|
||||
index = hit.get("_index", "")
|
||||
source = hit.get("_source", {})
|
||||
|
||||
program_type = _determine_program_type_from_index(index)
|
||||
project_type = EuCordisProjectType.from_index_name(index)
|
||||
|
||||
enrichers = {
|
||||
"fp7": _enrich_fp7_project,
|
||||
"h2020": _enrich_h2020_project,
|
||||
"heu": _enrich_heu_project,
|
||||
EuCordisProjectType.FP7: _enrich_fp7_project,
|
||||
EuCordisProjectType.H2020: _enrich_h2020_project,
|
||||
EuCordisProjectType.HEU: _enrich_heu_project,
|
||||
}
|
||||
|
||||
enricher = enrichers.get(program_type)
|
||||
enricher = enrichers.get(project_type)
|
||||
if enricher is None:
|
||||
logger.warning(f"Unknown programme type for index: {index}")
|
||||
return CordisEuProject.model_validate(source)
|
||||
|
||||
return await enricher(project_id, source)
|
||||
return await enricher(project_id, source, project_type)
|
||||
|
||||
# helpers
|
||||
def _determine_program_type_from_index(index: str) -> str:
|
||||
"""Determines the programme type from the Elasticsearch index name."""
|
||||
index_lower = index.lower()
|
||||
if "fp7" in index_lower:
|
||||
return "fp7"
|
||||
if "horizon_2020" in index_lower:
|
||||
return "h2020"
|
||||
if "heu" in index_lower or "horizon_europe" in index_lower:
|
||||
return "heu"
|
||||
return "unknown"
|
||||
|
||||
async def _fetch_authors_and_topics_for_project(
|
||||
project_id: str,
|
||||
project_type: EuCordisProjectType,
|
||||
) -> Tuple[Optional[AuthorPage], List[Topic]]:
|
||||
"""Fetches OpenAlex authors and mapped topics for a single project."""
|
||||
authors_lookup, topics_lookup = await asyncio.gather(
|
||||
get_openalex_authors_for_projects_ids({project_type: [project_id]}),
|
||||
get_openalex_topics_for_eu_projects({project_type: [project_id]}),
|
||||
)
|
||||
|
||||
author_page = authors_lookup.get((project_type, project_id))
|
||||
|
||||
raw_topic_matches = sorted(
|
||||
topics_lookup.get((project_type, project_id), []),
|
||||
key=lambda t: t.get("rank") if t.get("rank") is not None else float("inf"),
|
||||
)
|
||||
topics = [
|
||||
EuCordisProjectSummary.topic_from_match(match)
|
||||
for match in raw_topic_matches
|
||||
if isinstance(match, dict)
|
||||
]
|
||||
|
||||
return author_page, topics
|
||||
|
||||
async def _fetch_related_entities_parallel(
|
||||
project_id: str,
|
||||
@@ -244,10 +246,10 @@ async def _fetch_related_entities(
|
||||
|
||||
return grouped
|
||||
|
||||
|
||||
async def _enrich_fp7_project(
|
||||
project_id: str,
|
||||
project_source: Dict[str, Any],
|
||||
project_type: EuCordisProjectType,
|
||||
) -> Optional[Fp7ProjectDetails]:
|
||||
"""Enriches a single FP7 project with all related data."""
|
||||
try:
|
||||
@@ -256,41 +258,97 @@ async def _enrich_fp7_project(
|
||||
logger.error(f"Failed to validate FP7 project {project_id}: {e}")
|
||||
return None
|
||||
|
||||
related = await _fetch_related_entities_parallel(project_id, _FP7_ENTITY_CONFIGS)
|
||||
related, (authors, topics) = await asyncio.gather(
|
||||
_fetch_related_entities_parallel(project_id, _FP7_ENTITY_CONFIGS),
|
||||
_fetch_authors_and_topics_for_project(project_id, project_type),
|
||||
)
|
||||
|
||||
return Fp7ProjectDetails.from_project_with_relations(project=project, **related)
|
||||
return Fp7ProjectDetails.from_project_with_relations(
|
||||
project=project, oa_authors=authors, oa_topics=topics, **related
|
||||
)
|
||||
|
||||
|
||||
async def _enrich_h2020_project(
|
||||
project_id: str,
|
||||
project_source: Dict[str, Any],
|
||||
project_type: EuCordisProjectType,
|
||||
) -> Optional[H2020ProjectDetails]:
|
||||
"""Enriches a single H2020 project with all related data."""
|
||||
try:
|
||||
project = H2020Project.model_validate(project_source)
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to validate H2020 project {project_id}: {e}")
|
||||
return None
|
||||
|
||||
related = await _fetch_related_entities_parallel(project_id, _H2020_ENTITY_CONFIGS)
|
||||
related, (authors, topics) = await asyncio.gather(
|
||||
_fetch_related_entities_parallel(project_id, _H2020_ENTITY_CONFIGS),
|
||||
_fetch_authors_and_topics_for_project(project_id, project_type),
|
||||
)
|
||||
|
||||
return H2020ProjectDetails.from_project_with_relations(project=project, **related)
|
||||
return H2020ProjectDetails.from_project_with_relations(
|
||||
project=project, oa_authors=authors, oa_topics=topics, **related
|
||||
)
|
||||
|
||||
|
||||
async def _enrich_heu_project(
|
||||
project_id: str,
|
||||
project_source: Dict[str, Any],
|
||||
project_type: EuCordisProjectType,
|
||||
) -> Optional[HEUProjectDetails]:
|
||||
"""Enriches a single Horizon Europe project with all related data."""
|
||||
try:
|
||||
project = HEUProject.model_validate(project_source)
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to validate Horizon Europe project {project_id}: {e}")
|
||||
return None
|
||||
|
||||
related = await _fetch_related_entities_parallel(project_id, _HEU_ENTITY_CONFIGS)
|
||||
related, (authors, topics) = await asyncio.gather(
|
||||
_fetch_related_entities_parallel(project_id, _HEU_ENTITY_CONFIGS),
|
||||
_fetch_authors_and_topics_for_project(project_id, project_type),
|
||||
)
|
||||
|
||||
return HEUProjectDetails.from_project_with_relations(project=project, **related)
|
||||
return HEUProjectDetails.from_project_with_relations(
|
||||
project=project, oa_authors=authors, oa_topics=topics, **related
|
||||
)
|
||||
|
||||
async def _enrich_h2020_project(
|
||||
project_id: str,
|
||||
project_source: Dict[str, Any],
|
||||
project_type: EuCordisProjectType,
|
||||
) -> Optional[H2020ProjectDetails]:
|
||||
try:
|
||||
project = H2020Project.model_validate(project_source)
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to validate H2020 project {project_id}: {e}")
|
||||
return None
|
||||
|
||||
related, (authors, topics) = await asyncio.gather(
|
||||
_fetch_related_entities_parallel(project_id, _H2020_ENTITY_CONFIGS),
|
||||
_fetch_authors_and_topics_for_project(project_id, project_type),
|
||||
)
|
||||
|
||||
return H2020ProjectDetails.from_project_with_relations(
|
||||
project=project, oa_authors=authors, oa_topics=topics, **related
|
||||
)
|
||||
|
||||
|
||||
async def _enrich_heu_project(
|
||||
project_id: str,
|
||||
project_source: Dict[str, Any],
|
||||
project_type: EuCordisProjectType,
|
||||
) -> Optional[HEUProjectDetails]:
|
||||
try:
|
||||
project = HEUProject.model_validate(project_source)
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to validate Horizon Europe project {project_id}: {e}")
|
||||
return None
|
||||
|
||||
related, (authors, topics) = await asyncio.gather(
|
||||
_fetch_related_entities_parallel(project_id, _HEU_ENTITY_CONFIGS),
|
||||
_fetch_authors_and_topics_for_project(project_id, project_type),
|
||||
)
|
||||
|
||||
return HEUProjectDetails.from_project_with_relations(
|
||||
project=project, oa_authors=authors, oa_topics=topics, **related
|
||||
)
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -74,6 +74,73 @@ async def get_person_ids_by_institution_ids(
|
||||
if hit.get("_source", {}).get("person_id") is not None
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
async def get_bund_project_ids_by_topic_ids(topic_ids: List[str]) -> List[str]:
|
||||
"""
|
||||
Query the `projects_bund_openalex_topics` index to find BUND project IDs
|
||||
that match any of the given OpenAlex topic IDs.
|
||||
"""
|
||||
if not topic_ids:
|
||||
return []
|
||||
|
||||
required_topics = set(topic_ids)
|
||||
|
||||
project_topics: dict[str, Set[str]] = defaultdict(set)
|
||||
|
||||
page_size = 1000
|
||||
from_ = 0
|
||||
|
||||
while True:
|
||||
body = {
|
||||
"size": page_size,
|
||||
"from": from_,
|
||||
"_source": ["project_id", "topic_matches"],
|
||||
"query": {
|
||||
"terms": {
|
||||
"topic_matches.topic_id.keyword": topic_ids
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.PROJECTS_BUND_TOPICS,
|
||||
cluster=ESCluster.INSE,
|
||||
body=body,
|
||||
)
|
||||
print(f"Response from Elasticsearch: {json.dumps(response, indent=2)}") # Debugging line
|
||||
hits = response.get("hits", {}).get("hits", [])
|
||||
if not hits:
|
||||
break
|
||||
|
||||
for hit in hits:
|
||||
source = hit["_source"]
|
||||
|
||||
project_id = source.get("project_id")
|
||||
if not project_id:
|
||||
continue
|
||||
|
||||
topic_matches = source.get("topic_matches") or []
|
||||
|
||||
if isinstance(topic_matches, dict):
|
||||
topic_matches = [topic_matches]
|
||||
|
||||
for match in topic_matches:
|
||||
topic_id = match.get("topic_id")
|
||||
if topic_id in required_topics:
|
||||
project_topics[project_id].add(topic_id)
|
||||
|
||||
if len(hits) < page_size:
|
||||
break
|
||||
|
||||
from_ += page_size
|
||||
|
||||
return [
|
||||
project_id
|
||||
for project_id, found_topics in project_topics.items()
|
||||
if required_topics.issubset(found_topics)
|
||||
]
|
||||
|
||||
async def get_dfg_project_ids_by_topic_ids(topic_ids: List[str]) -> List[str]:
|
||||
"""Fetches project IDs whose topic_matches contain EVERY given topic ID,
|
||||
even if the topics are distributed across multiple documents for the same project.
|
||||
@@ -137,63 +204,73 @@ async def get_dfg_project_ids_by_topic_ids(topic_ids: List[str]) -> List[str]:
|
||||
for project_id, found_topics in project_topics.items()
|
||||
if required_topics.issubset(found_topics)
|
||||
]
|
||||
async def get_openalex_topics_for_dfg_projects(
|
||||
project_ids: List[str],
|
||||
) -> Dict[int, List[Dict[str, Any]]]:
|
||||
"""Fetches OpenAlex topic matches for the given DFG project IDs.
|
||||
|
||||
|
||||
Args:
|
||||
project_ids (List[str]): The DFG project IDs to fetch topics for.
|
||||
|
||||
Returns:
|
||||
Dict[int, List[Dict[str, Any]]]: Mapping of project_id -> list of topic match dicts,
|
||||
each containing topic_id, topic_display_name, domain, field, subfield, rank.
|
||||
async def get_openalex_topics_for_bund_projects(project_ids: List[str]) -> Dict[str, List[Dict]]:
|
||||
"""
|
||||
Retrieve OpenAlex topic details for a list of BUND project IDs.
|
||||
Returns a dict mapping `project_id` -> list of topic_match objects.
|
||||
"""
|
||||
if not project_ids:
|
||||
return {}
|
||||
|
||||
topic_lookup: Dict[int, List[Dict[str, Any]]] = {}
|
||||
body: Dict[str, Any] = {
|
||||
"size": 10000,
|
||||
"query": {
|
||||
"terms": {
|
||||
"project_id.keyword": project_ids
|
||||
}
|
||||
},
|
||||
"_source": ["project_id", "topic_matches"]
|
||||
}
|
||||
|
||||
page_size = 1000
|
||||
from_ = 0
|
||||
# print(f"Fetching topics for {len(project_ids)} DFG projects in batches of {page_size}...{project_ids}")
|
||||
while True:
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.PROJECTS_DFG_TOPICS,
|
||||
cluster=ESCluster.INSE,
|
||||
body={
|
||||
"size": page_size,
|
||||
"from": from_,
|
||||
"query": {
|
||||
"terms": {
|
||||
"project_id.keyword": project_ids
|
||||
}
|
||||
},
|
||||
},
|
||||
)
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.PROJECTS_BUND_TOPICS,
|
||||
body=body,
|
||||
cluster=ESCluster.INSE
|
||||
)
|
||||
|
||||
hits = response.get("hits", {}).get("hits", [])
|
||||
if not hits:
|
||||
break
|
||||
lookup: Dict[str, List[Dict]] = {}
|
||||
for hit in response.get("hits", {}).get("hits", []):
|
||||
src = hit["_source"]
|
||||
pid = src.get("project_id")
|
||||
if pid:
|
||||
lookup[pid] = src.get("topic_matches", [])
|
||||
return lookup
|
||||
async def get_openalex_topics_for_dfg_projects(
|
||||
project_ids: List[str],
|
||||
) -> Dict[str, List[Dict]]:
|
||||
"""
|
||||
Retrieve OpenAlex topic details for a list of DFG project IDs.
|
||||
Returns a dict mapping `project_id` -> list of topic_match objects.
|
||||
"""
|
||||
if not project_ids:
|
||||
return {}
|
||||
|
||||
for hit in hits:
|
||||
source = hit["_source"]
|
||||
project_id = int(source.get("project_id"))
|
||||
if project_id is None:
|
||||
continue
|
||||
body: Dict[str, Any] = {
|
||||
"size": 10000,
|
||||
"query": {
|
||||
"terms": {
|
||||
"project_id.keyword": project_ids
|
||||
}
|
||||
},
|
||||
"_source": ["project_id", "topic_matches"]
|
||||
}
|
||||
|
||||
topic_matches = source.get("topic_matches") or []
|
||||
if isinstance(topic_matches, dict):
|
||||
topic_matches = [topic_matches]
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.PROJECTS_DFG_TOPICS,
|
||||
body=body,
|
||||
cluster=ESCluster.INSE
|
||||
)
|
||||
|
||||
topic_lookup.setdefault(project_id, []).extend(topic_matches)
|
||||
lookup: Dict[str, List[Dict]] = {}
|
||||
for hit in response.get("hits", {}).get("hits", []):
|
||||
src = hit["_source"]
|
||||
pid = src.get("project_id")
|
||||
if pid:
|
||||
lookup[str(pid)] = src.get("topic_matches", [])
|
||||
|
||||
if len(hits) < page_size:
|
||||
break
|
||||
|
||||
from_ += page_size
|
||||
#logger.info(f"Fetched topics for {len(topic_lookup)} DFG projects.")
|
||||
return topic_lookup
|
||||
return lookup
|
||||
|
||||
async def get_person_institutes(
|
||||
person_ids: list[int],
|
||||
|
||||
@@ -14,6 +14,7 @@ from inse.models.projects_eu_cordis.fp7.fp7_project_details import Fp7ProjectDet
|
||||
from inse.models.projects_dfg_v2.project.dfg_project_fachgebiete_inner import DFGProjectFachgebieteInner
|
||||
from inse.models.openalex.topic import Topic, TopicDomain, TopicField, TopicSubfield
|
||||
from inse.authors.v2.model import AuthorPage
|
||||
from inse.projects.bund_institutions.model import BundInstitutionSummary
|
||||
from typing import Union
|
||||
|
||||
class ProjectType(StrEnum):
|
||||
@@ -75,6 +76,11 @@ class BundProjectSummary(BundProject):
|
||||
description="The OpenAlex topics of the project",
|
||||
examples=[["Artificial Intelligence", "Machine Learning"]],
|
||||
)
|
||||
institution: Optional[BundInstitutionSummary] = Field(
|
||||
default=None,
|
||||
description="The executing agency / recipient institution for this project, "
|
||||
"derived from the project's own agency fields.",
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def from_hit(cls, hit: dict) -> "BundProjectSummary":
|
||||
@@ -91,7 +97,6 @@ class BundProjectSummary(BundProject):
|
||||
key=lambda t: t.get("rank") if t.get("rank") is not None else float("inf"),
|
||||
)
|
||||
oa_topics = [cls._topic_from_match(t) for t in sorted_topics_raw]
|
||||
print(f"oa_topics: {oa_topics}")
|
||||
return cls(
|
||||
funding_code=source.get("Förderkennzeichen"),
|
||||
department=source.get("Ressort"),
|
||||
@@ -110,8 +115,8 @@ class BundProjectSummary(BundProject):
|
||||
topic=source.get("Thema"),
|
||||
performance_plan_system=source.get("Leistungsplansystematik"),
|
||||
performance_plan_system_text=source.get("Klartext Leistungsplansystematik"),
|
||||
funding_start=source.get("Förderbeginn"),
|
||||
funding_end=source.get("Förderende"),
|
||||
funding_start=source.get("funding_start"),
|
||||
funding_end=source.get("funding_end"),
|
||||
grant_amount=source.get("Fördersumme"),
|
||||
funding_profile=source.get("Förderprofil"),
|
||||
joint_project=source.get("Verbundprojekt"),
|
||||
@@ -122,6 +127,7 @@ class BundProjectSummary(BundProject):
|
||||
new=source.get("neu"),
|
||||
duration=source.get("Laufzeit"),
|
||||
oa_topics=oa_topics,
|
||||
institution=BundInstitutionSummary.from_source(source),
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
|
||||
@@ -21,7 +21,7 @@ from inse.models.dfg_project_details import DfgProjectDetails
|
||||
from inse.models.bund_project_details import BundProjectDetails
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESCluster, ESIndex
|
||||
from inse.projects.logic import get_person_ids_by_institution_ids, get_dfg_project_ids_by_topic_ids, get_openalex_topics_for_dfg_projects, get_person_institutes
|
||||
from inse.projects.logic import get_person_ids_by_institution_ids, get_dfg_project_ids_by_topic_ids,get_bund_project_ids_by_topic_ids, get_openalex_topics_for_dfg_projects, get_person_institutes, get_openalex_topics_for_bund_projects
|
||||
|
||||
settings = get_settings()
|
||||
|
||||
@@ -29,66 +29,6 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
logger.setLevel(settings.logging_level)
|
||||
|
||||
DFG_PERSON_FIELDS: List[str] = [
|
||||
"Antragsteller",
|
||||
"Antragstellerin",
|
||||
"Antragstellerinnen",
|
||||
"Antragstellerinnen / Antragsteller",
|
||||
"Beteiligte Person",
|
||||
"Beteiligte Personen",
|
||||
"Co-Sprecher",
|
||||
"Co-Sprecherinnen / Co-Sprecher",
|
||||
"Ehemalige Antragsteller",
|
||||
"Ehemalige Antragstellerin",
|
||||
"Ehemalige Antragstellerinnen",
|
||||
"Ehemalige Antragstellerinnen / Ehemalige Antragsteller",
|
||||
"Ehemaliger Antragsteller",
|
||||
"Gastgeber",
|
||||
"Gastgeberin",
|
||||
"Gastgeberinnen",
|
||||
"Gastgeberinnen / Gastgeber",
|
||||
"Kooperationspartner",
|
||||
"Kooperationspartnerin",
|
||||
"Kooperationspartnerinnen",
|
||||
"Kooperationspartnerinnen / Kooperationspartner",
|
||||
"Leiter",
|
||||
"Leiterin",
|
||||
"Leiterinnen",
|
||||
"Leiterinnen / Leiter",
|
||||
"Mitantragsteller",
|
||||
"Mitantragstellerin",
|
||||
"Mitantragstellerinnen",
|
||||
"Mitantragstellerinnen / Mitantragsteller",
|
||||
"Mitverantwortlich",
|
||||
"Mitverantwortlich(e)",
|
||||
"Mitverantwortliche",
|
||||
"Sprecher",
|
||||
"Sprecher (IGK-Partner)",
|
||||
"Sprecherin",
|
||||
"Sprecherin (IGK-Partner)",
|
||||
"Sprecherinnen",
|
||||
"Sprecherinnen (IGK-Partner) / Sprecher (IGK-Partner)",
|
||||
"Sprecherinnen / Sprecher",
|
||||
"Teilprojektleiter",
|
||||
"Teilprojektleiterin",
|
||||
"Teilprojektleiterinnen",
|
||||
"Teilprojektleiterinnen / Teilprojektleiter",
|
||||
"ausländ. Mitantragstellerin",
|
||||
"ausländ. Mitantragstellerinnen",
|
||||
"ausländ. Mitantragstellerinnen / ausländische Mitantragsteller",
|
||||
"ausländische Mitantragsteller",
|
||||
"ausländischer Mitantragsteller",
|
||||
"beteiligte Wissenschaftler",
|
||||
"beteiligte Wissenschaftlerin",
|
||||
"beteiligte Wissenschaftlerinnen",
|
||||
"beteiligte Wissenschaftlerinnen / beteiligte Wissenschaftler",
|
||||
"beteiligter Wissenschaftler",
|
||||
"person_creater_name",
|
||||
"stellvertr. Sprecher",
|
||||
"stellvertr. Sprecherin",
|
||||
"stellvertr. Sprecherinnen / stellvertr. Sprecher",
|
||||
]
|
||||
|
||||
# BUND
|
||||
|
||||
|
||||
@@ -204,10 +144,13 @@ async def get_bund_project_by_id(project_id: str) -> Optional[BundProjectDetails
|
||||
query=query,
|
||||
size=1,
|
||||
)
|
||||
|
||||
|
||||
hits = response.get("hits", {}).get("hits", [])
|
||||
if hits:
|
||||
hit = hits[0]
|
||||
elastic_id = hit["_id"]
|
||||
topic_lookup = await get_openalex_topics_for_bund_projects(project_ids=[elastic_id])
|
||||
hit["_source"]["oa_topics"] = topic_lookup.get(elastic_id, [])
|
||||
details = BundProjectDetails.from_elastic_hit(hit=hit)
|
||||
return details
|
||||
return None
|
||||
@@ -679,6 +622,7 @@ async def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]:
|
||||
Returns:
|
||||
Optional[DfgProjectDetails]: The project details or None if not found.
|
||||
"""
|
||||
topic_lookup = await get_openalex_topics_for_dfg_projects(project_ids=[project_id])
|
||||
query = {"ids": {"values": [project_id]}}
|
||||
|
||||
response = await elasticsearch.search(
|
||||
@@ -690,79 +634,42 @@ async def get_dfg_project_by_id(project_id: str) -> Optional[DfgProjectDetails]:
|
||||
|
||||
if hits:
|
||||
hit = hits[0]
|
||||
hit["_source"]["topics"] = topic_lookup.get(project_id, [])
|
||||
details = DfgProjectDetails.from_elastic_hit(hit=hit)
|
||||
return details
|
||||
return None
|
||||
|
||||
#BUND
|
||||
|
||||
async def get_bund_project_ids_by_topic_ids(topic_ids: List[str]) -> List[str]:
|
||||
"""
|
||||
Query the `projects_bund_openalex_topics` index to find BUND project IDs
|
||||
that match any of the given OpenAlex topic IDs.
|
||||
"""
|
||||
body: Dict[str, Any] = {
|
||||
"size": 0,
|
||||
"query": {
|
||||
"terms": {
|
||||
"topic_matches.topic_id": topic_ids
|
||||
}
|
||||
},
|
||||
"aggs": {
|
||||
"project_ids": {
|
||||
"terms": {
|
||||
"field": "project_id.keyword",
|
||||
"size": 10000
|
||||
def _bund_year_filters(field: str, years: List[str]) -> Dict[str, Any]:
|
||||
should = []
|
||||
|
||||
for year in years:
|
||||
year = str(year).strip()
|
||||
if not year:
|
||||
continue
|
||||
|
||||
should.append(
|
||||
{
|
||||
"range": {
|
||||
field: {
|
||||
"gte": f"01.01.{year}",
|
||||
"lte": f"31.12.{year}",
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
return {
|
||||
"bool": {
|
||||
"should": should,
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.PROJECTS_BUND_TOPICS,
|
||||
body=body,
|
||||
cluster=ESCluster.INSE
|
||||
)
|
||||
print(f"Received response for topic_ids {topic_ids}: {json.dumps(response, indent=2)}")
|
||||
buckets = response.get("aggregations", {}).get("project_ids", {}).get("buckets", [])
|
||||
return [bucket["key"] for bucket in buckets]
|
||||
|
||||
|
||||
async def get_openalex_topics_for_bund_projects(project_ids: List[str]) -> Dict[str, List[Dict]]:
|
||||
"""
|
||||
Retrieve OpenAlex topic details for a list of BUND project IDs.
|
||||
Returns a dict mapping `project_id` -> list of topic_match objects.
|
||||
"""
|
||||
if not project_ids:
|
||||
return {}
|
||||
|
||||
body: Dict[str, Any] = {
|
||||
"size": 10000,
|
||||
"query": {
|
||||
"terms": {
|
||||
"project_id.keyword": project_ids
|
||||
}
|
||||
},
|
||||
"_source": ["project_id", "topic_matches"]
|
||||
}
|
||||
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.PROJECTS_BUND_TOPICS,
|
||||
body=body,
|
||||
cluster=ESCluster.INSE
|
||||
)
|
||||
|
||||
lookup: Dict[str, List[Dict]] = {}
|
||||
for hit in response.get("hits", {}).get("hits", []):
|
||||
src = hit["_source"]
|
||||
pid = src.get("project_id")
|
||||
if pid:
|
||||
lookup[pid] = src.get("topic_matches", [])
|
||||
return lookup
|
||||
|
||||
|
||||
async def search_bund_projects_with_filters(
|
||||
executing_agency: Optional[List[str]] = None,
|
||||
institution_ids: Optional[List[int]] = None,
|
||||
institution_ids: Optional[List[str]] = None,
|
||||
funding_arts: Optional[List[str]] = None, # actually EuCordisProjectType, but treated as strings
|
||||
title: Optional[str] = None,
|
||||
keywords: Optional[List[str]] = None,
|
||||
@@ -781,7 +688,7 @@ async def search_bund_projects_with_filters(
|
||||
Main search function for BUND projects, analogous to the DFG search.
|
||||
"""
|
||||
from_ = page * size
|
||||
|
||||
#institution_ids = ["I62318514"]
|
||||
# Fields we need to build BundProject objects (validation aliases match these exact names)
|
||||
source_fields = [
|
||||
"Förderkennzeichen",
|
||||
@@ -812,7 +719,6 @@ async def search_bund_projects_with_filters(
|
||||
"datum",
|
||||
"neu",
|
||||
"Laufzeit",
|
||||
# Also include funding_start/end for sorting and filtering (they may also be needed)
|
||||
"funding_start",
|
||||
"funding_end",
|
||||
]
|
||||
@@ -825,13 +731,12 @@ async def search_bund_projects_with_filters(
|
||||
}
|
||||
|
||||
must_clauses: List[Dict[str, Any]] = []
|
||||
|
||||
# === Primary search clause: fuzzy(topic_ids) vs keyword phrase search ===
|
||||
if fuzzy and topic_ids:
|
||||
matching_project_ids = await get_bund_project_ids_by_topic_ids(topic_ids=topic_ids)
|
||||
if not matching_project_ids:
|
||||
return BundProjectPage(elements=[], total=0, page=page, size=size)
|
||||
must_clauses.append({"terms": {"Förderkennzeichen.keyword": matching_project_ids}})
|
||||
must_clauses.append({"terms": {"_id": matching_project_ids}})
|
||||
|
||||
elif keywords:
|
||||
keyword_clauses = []
|
||||
@@ -841,7 +746,7 @@ async def search_bund_projects_with_filters(
|
||||
keyword_clauses.append({
|
||||
"multi_match": {
|
||||
"query": kw,
|
||||
"fields": ["Verbundprojekt"], # searching title/acronym field
|
||||
"fields": ["Verbundprojekt","Thema"], # searching title/acronym field
|
||||
"type": "phrase_prefix",
|
||||
"max_expansions": 100,
|
||||
}
|
||||
@@ -854,21 +759,38 @@ async def search_bund_projects_with_filters(
|
||||
matching_filter_ids = await get_bund_project_ids_by_topic_ids(topic_ids=filter_topic_ids)
|
||||
if not matching_filter_ids:
|
||||
return BundProjectPage(elements=[], total=0, page=page, size=size)
|
||||
must_clauses.append({"terms": {"Förderkennzeichen.keyword": matching_filter_ids}})
|
||||
must_clauses.append({"terms": {"_id": matching_filter_ids}})
|
||||
|
||||
if title:
|
||||
must_clauses.append({
|
||||
"multi_match": {
|
||||
"query": title,
|
||||
"fields": ["Verbundprojekt"],
|
||||
"fields": ["Verbundprojekt","Thema"], # searching title field
|
||||
"type": "phrase_prefix",
|
||||
"max_expansions": 100,
|
||||
}
|
||||
})
|
||||
|
||||
# print(f"Executing BUND project search with institution_ids: {institution_ids}, executing_agency: {executing_agency}, funding_arts: {funding_arts}, countries: {countries}, funding_start_years: {funding_start_years}, funding_end_years: {funding_end_years}")
|
||||
if executing_agency:
|
||||
must_clauses.append({"terms": {"Ausführende Stelle.keyword": executing_agency}})
|
||||
|
||||
# institution_names = await institutions_search_client.get_institution_aliases_by_oa_institution_id(executing_agency[0].split("/")[-1])
|
||||
# institution_page = await institutions_search_client.get_institutions_by_alias(alias=institution_names[0])
|
||||
# print(f"Retrieved institution names for IDs {executing_agency}: {institution_names}")
|
||||
# print(f"Retrieved institution page for names {institution_names}: {institution_page}")
|
||||
# if not institution_names:
|
||||
# return BundProjectPage(elements=[], total=0, page=page, size=size)
|
||||
must_clauses.append({
|
||||
"bool": {
|
||||
"should": [
|
||||
clause
|
||||
for name in executing_agency
|
||||
for clause in (
|
||||
{"match": {"Zuwendungsempfänger": {"query": name, "operator": "and"}}},
|
||||
{"match": {"Ausführende Stelle": {"query": name, "operator": "and"}}},
|
||||
)
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
})
|
||||
if funding_arts:
|
||||
must_clauses.append({"terms": {"Förderart.keyword": funding_arts}})
|
||||
|
||||
@@ -876,10 +798,10 @@ async def search_bund_projects_with_filters(
|
||||
must_clauses.append({"terms": {"Staat.keyword": countries}})
|
||||
|
||||
if funding_start_years:
|
||||
must_clauses.append({"terms": {"funding_start": funding_start_years}})
|
||||
must_clauses.append(_bund_year_filters("funding_start", funding_start_years))
|
||||
|
||||
if funding_end_years:
|
||||
must_clauses.append({"terms": {"funding_end": funding_end_years}})
|
||||
must_clauses.append(_bund_year_filters("funding_end", funding_end_years))
|
||||
|
||||
body["query"] = {"bool": {"must": must_clauses}} if must_clauses else {"match_all": {}}
|
||||
|
||||
@@ -914,7 +836,6 @@ async def search_bund_projects_with_filters(
|
||||
# Enrich with OpenAlex topics
|
||||
project_ids = [hit["_id"] for hit in hits]
|
||||
topic_lookup = await get_openalex_topics_for_bund_projects(project_ids=project_ids)
|
||||
print(f"Enriched BUND projects with topics: {json.dumps(topic_lookup, indent=2)}")
|
||||
for hit in hits:
|
||||
hit["_source"]["oa_topics"] = topic_lookup.get(hit["_id"], [])
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ async def test_search_dfg_projects():
|
||||
res = await projects_search_client.search_dfg_projects(
|
||||
page=0,
|
||||
size=5,
|
||||
names=["Wolfgang Ahrens"],
|
||||
names=["Bovensiepen"],
|
||||
)
|
||||
assert res is not None
|
||||
assert res.total > 0
|
||||
@@ -15,23 +15,19 @@ async def test_search_dfg_projects():
|
||||
for element in res.elements:
|
||||
assert element.id is not None
|
||||
assert any(
|
||||
all(part.lower() in name.lower() for part in "Wolfgang Ahrens".split())
|
||||
all(part.lower() in name.lower() for part in "Bovensiepen".split())
|
||||
for name in element.names
|
||||
)
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_get_dfg_project_by_id():
|
||||
# Get by ID of the project we found or a known one
|
||||
known_id = "164008977"
|
||||
known_id = 164008977
|
||||
project = await projects_search_client.get_dfg_project_by_id(known_id)
|
||||
assert project is not None
|
||||
assert project.id == known_id
|
||||
assert project.title is not None
|
||||
assert project.title_de is not None
|
||||
assert any(
|
||||
all(part.lower() in person.lower() for part in "Wolfgang Ahrens".split())
|
||||
for person in project.associated_persons
|
||||
)
|
||||
assert any(
|
||||
"Leibniz" in inst
|
||||
for inst in project.institutions
|
||||
all(part.lower() in person.full_name.lower() for part in "Wolfgang Ahrens".split())
|
||||
for person in project.persons
|
||||
)
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
from decimal import Decimal, ROUND_HALF_UP
|
||||
from typing import Any
|
||||
|
||||
from inse.authors.v2.service import authors_currently_belong_to_institution
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESIndex
|
||||
from inse.works.v2.model import WorkPrimaryCategory
|
||||
|
||||
from .model import PublicationType, Timespan
|
||||
from .orientation_profile_model import (
|
||||
AuthorOrientationProfile,
|
||||
AuthorOrientationProfileStatus,
|
||||
)
|
||||
|
||||
|
||||
_SCORE_FIELD = "classification.applied_orientation_score"
|
||||
_PRIMARY_CATEGORY_VALUES = {
|
||||
category.value for category in WorkPrimaryCategory
|
||||
}
|
||||
|
||||
|
||||
def _author_filter(author_ids: list[str]) -> dict[str, Any]:
|
||||
return {
|
||||
"nested": {
|
||||
"path": "authors",
|
||||
"query": {"terms": {"authors.id": author_ids}},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def _orientation_profile_query(
|
||||
author_ids: list[str],
|
||||
publication_types: list[PublicationType],
|
||||
timespan: Timespan | None,
|
||||
) -> dict[str, Any]:
|
||||
filters: list[dict[str, Any]] = [_author_filter(author_ids)]
|
||||
|
||||
if publication_types:
|
||||
filters.append(
|
||||
{
|
||||
"terms": {
|
||||
"publication_type": [
|
||||
publication_type.value
|
||||
for publication_type in publication_types
|
||||
]
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
if timespan:
|
||||
filters.append(
|
||||
{
|
||||
"range": {
|
||||
"publication_year": {
|
||||
"gte": timespan.from_year,
|
||||
"lte": timespan.to_year,
|
||||
}
|
||||
}
|
||||
}
|
||||
)
|
||||
|
||||
return {
|
||||
"size": 0,
|
||||
"query": {"bool": {"filter": filters}},
|
||||
"aggs": {
|
||||
"authors": {
|
||||
"nested": {"path": "authors"},
|
||||
"aggs": {
|
||||
"selected": {
|
||||
"filter": {"terms": {"authors.id": author_ids}},
|
||||
"aggs": {
|
||||
"by_author": {
|
||||
"terms": {
|
||||
"field": "authors.id",
|
||||
"size": len(author_ids),
|
||||
"execution_hint": "map",
|
||||
},
|
||||
"aggs": {
|
||||
"works": {
|
||||
"reverse_nested": {},
|
||||
"aggs": {
|
||||
"classified": {
|
||||
"filter": {
|
||||
"exists": {
|
||||
"field": (
|
||||
"classification."
|
||||
"primary_category"
|
||||
)
|
||||
}
|
||||
},
|
||||
"aggs": {
|
||||
"by_primary_category": {
|
||||
"terms": {
|
||||
"field": (
|
||||
"classification."
|
||||
"primary_category"
|
||||
),
|
||||
"size": len(
|
||||
WorkPrimaryCategory
|
||||
),
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
"scored": {
|
||||
"filter": {
|
||||
"exists": {
|
||||
"field": _SCORE_FIELD
|
||||
}
|
||||
},
|
||||
"aggs": {
|
||||
"average_score": {
|
||||
"avg": {
|
||||
"field": _SCORE_FIELD
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _rounded_score(value: float) -> int:
|
||||
return int(Decimal(str(value)).quantize(Decimal("1"), rounding=ROUND_HALF_UP))
|
||||
|
||||
|
||||
def _profile_from_bucket(
|
||||
author_id: str,
|
||||
bucket: dict[str, Any] | None,
|
||||
) -> AuthorOrientationProfile:
|
||||
works = (bucket or {}).get("works", {})
|
||||
classified_count = works.get("classified", {}).get("doc_count", 0)
|
||||
category_buckets = (
|
||||
works.get("classified", {})
|
||||
.get("by_primary_category", {})
|
||||
.get("buckets", [])
|
||||
)
|
||||
category_counts = {
|
||||
WorkPrimaryCategory(category_bucket["key"]): category_bucket["doc_count"]
|
||||
for category_bucket in category_buckets
|
||||
if category_bucket.get("key") in _PRIMARY_CATEGORY_VALUES
|
||||
}
|
||||
scored = works.get("scored", {})
|
||||
scored_count = scored.get("doc_count", 0)
|
||||
average_score = scored.get("average_score", {}).get("value")
|
||||
|
||||
if classified_count == 0:
|
||||
status = AuthorOrientationProfileStatus.NO_CLASSIFIED_PUBLICATIONS
|
||||
elif scored_count == 0 or average_score is None:
|
||||
status = AuthorOrientationProfileStatus.NO_ORIENTATION_SCORE
|
||||
else:
|
||||
score = _rounded_score(average_score)
|
||||
return AuthorOrientationProfile(
|
||||
author_id=author_id,
|
||||
status=AuthorOrientationProfileStatus.AVAILABLE,
|
||||
orientation_score=score,
|
||||
primary_category_counts=category_counts,
|
||||
classified_work_count=classified_count,
|
||||
scored_work_count=scored_count,
|
||||
)
|
||||
|
||||
return AuthorOrientationProfile(
|
||||
author_id=author_id,
|
||||
status=status,
|
||||
primary_category_counts=category_counts,
|
||||
classified_work_count=classified_count,
|
||||
scored_work_count=scored_count,
|
||||
)
|
||||
|
||||
|
||||
async def orientation_profiles_for_authors(
|
||||
author_ids: list[str],
|
||||
institution_id: str | None,
|
||||
publication_types: list[PublicationType],
|
||||
timespan: Timespan | None,
|
||||
) -> list[AuthorOrientationProfile]:
|
||||
"""Return protected orientation profiles in the requested author order.
|
||||
|
||||
Institution membership is checked for all authors in one query. Only
|
||||
matching active members are included in the work-classification
|
||||
aggregation, so restricted classification data is never retrieved.
|
||||
"""
|
||||
|
||||
if not institution_id:
|
||||
allowed_author_ids: set[str] = set()
|
||||
else:
|
||||
allowed_author_ids = await authors_currently_belong_to_institution(
|
||||
author_ids,
|
||||
institution_id,
|
||||
)
|
||||
|
||||
restricted_profiles = {
|
||||
author_id: AuthorOrientationProfile(
|
||||
author_id=author_id,
|
||||
status=AuthorOrientationProfileStatus.RESTRICTED,
|
||||
)
|
||||
for author_id in author_ids
|
||||
if author_id not in allowed_author_ids
|
||||
}
|
||||
|
||||
allowed_in_request_order = [
|
||||
author_id for author_id in author_ids if author_id in allowed_author_ids
|
||||
]
|
||||
profiles_by_id: dict[str, AuthorOrientationProfile] = restricted_profiles
|
||||
|
||||
if allowed_in_request_order:
|
||||
response = await elasticsearch.search(
|
||||
index=ESIndex.WORK_CLASSIFICATIONS,
|
||||
body=_orientation_profile_query(
|
||||
allowed_in_request_order,
|
||||
publication_types,
|
||||
timespan,
|
||||
),
|
||||
)
|
||||
buckets = (
|
||||
response.get("aggregations", {})
|
||||
.get("authors", {})
|
||||
.get("selected", {})
|
||||
.get("by_author", {})
|
||||
.get("buckets", [])
|
||||
)
|
||||
buckets_by_author = {
|
||||
bucket.get("key"): bucket
|
||||
for bucket in buckets
|
||||
if isinstance(bucket.get("key"), str)
|
||||
}
|
||||
for author_id in allowed_in_request_order:
|
||||
profiles_by_id[author_id] = _profile_from_bucket(
|
||||
author_id,
|
||||
buckets_by_author.get(author_id),
|
||||
)
|
||||
|
||||
return [profiles_by_id[author_id] for author_id in author_ids]
|
||||
@@ -0,0 +1,78 @@
|
||||
from enum import StrEnum
|
||||
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
|
||||
from inse.works.v2.model import WorkPrimaryCategory
|
||||
|
||||
from .model import PublicationType, Timespan
|
||||
|
||||
|
||||
class AuthorOrientationProfileStatus(StrEnum):
|
||||
AVAILABLE = "available"
|
||||
INSUFFICIENT_SCORED_PUBLICATIONS = "insufficient_scored_publications"
|
||||
NO_CLASSIFIED_PUBLICATIONS = "no_classified_publications"
|
||||
NO_ORIENTATION_SCORE = "no_orientation_score"
|
||||
RESTRICTED = "restricted"
|
||||
|
||||
|
||||
class AuthorOrientationProfilesRequest(BaseModel):
|
||||
"""Filters used to compare the research orientation of selected authors."""
|
||||
|
||||
author_ids: list[str] = Field(
|
||||
min_length=1,
|
||||
max_length=4,
|
||||
description="One to four unique OpenAlex author IDs.",
|
||||
)
|
||||
publication_types: list[PublicationType] = Field(
|
||||
default_factory=list,
|
||||
description="Optional publication-type filter. Empty means all types.",
|
||||
)
|
||||
timespan: Timespan | None = Field(
|
||||
default=None,
|
||||
description="Optional inclusive publication-year filter.",
|
||||
)
|
||||
|
||||
@field_validator("author_ids")
|
||||
@classmethod
|
||||
def normalize_author_ids(cls, values: list[str]) -> list[str]:
|
||||
normalized: list[str] = []
|
||||
for value in values:
|
||||
author_id = value.strip()
|
||||
if not author_id:
|
||||
raise ValueError("author IDs must not be empty")
|
||||
if not author_id.startswith("https://openalex.org/"):
|
||||
author_id = f"https://openalex.org/{author_id}"
|
||||
if author_id in normalized:
|
||||
raise ValueError("author IDs must be unique")
|
||||
normalized.append(author_id)
|
||||
return normalized
|
||||
|
||||
|
||||
class AuthorOrientationProfile(BaseModel):
|
||||
"""Aggregated research-orientation result for one selected author."""
|
||||
|
||||
author_id: str = Field(description="The full OpenAlex author ID.")
|
||||
status: AuthorOrientationProfileStatus
|
||||
orientation_score: int | None = Field(
|
||||
default=None,
|
||||
ge=0,
|
||||
le=100,
|
||||
description="Rounded mean score, available when at least one work has a score.",
|
||||
)
|
||||
primary_category_counts: dict[WorkPrimaryCategory, int] | None = Field(
|
||||
default=None,
|
||||
description=(
|
||||
"Matching work counts grouped by primary category; hidden when "
|
||||
"access is restricted."
|
||||
),
|
||||
)
|
||||
classified_work_count: int | None = Field(
|
||||
default=None,
|
||||
ge=0,
|
||||
description="Matching classified works; hidden when access is restricted.",
|
||||
)
|
||||
scored_work_count: int | None = Field(
|
||||
default=None,
|
||||
ge=0,
|
||||
description="Matching works with an orientation score; hidden when restricted.",
|
||||
)
|
||||
@@ -7,6 +7,11 @@ from inse.auth.model import AccessTokenMetadata
|
||||
from inse.auth.service import CurrentUserAccessTokenPayloadDep
|
||||
from inse.tags import Tags
|
||||
from . import logic
|
||||
from .orientation_profile_logic import orientation_profiles_for_authors
|
||||
from .orientation_profile_model import (
|
||||
AuthorOrientationProfile,
|
||||
AuthorOrientationProfilesRequest,
|
||||
)
|
||||
from .model import (
|
||||
AuthorMetricsRequest,
|
||||
AuthorStaticStats,
|
||||
@@ -117,3 +122,23 @@ async def static_stats(request: AuthorMetricsRequest):
|
||||
request.author_ids,
|
||||
request.company_status,
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/orientation-profiles",
|
||||
response_model=List[AuthorOrientationProfile],
|
||||
)
|
||||
async def orientation_profiles(
|
||||
request: AuthorOrientationProfilesRequest,
|
||||
access_token_metadata: Annotated[
|
||||
AccessTokenMetadata, CurrentUserAccessTokenPayloadDep
|
||||
],
|
||||
):
|
||||
"""Compare orientation scores for active members of the account institution."""
|
||||
|
||||
return await orientation_profiles_for_authors(
|
||||
author_ids=request.author_ids,
|
||||
institution_id=access_token_metadata.effective_institution_id,
|
||||
publication_types=request.publication_types,
|
||||
timespan=request.timespan,
|
||||
)
|
||||
|
||||
@@ -24,3 +24,5 @@ class Tags(StrEnum):
|
||||
DFG_INSTITUTIONS = "DFG Institutions"
|
||||
DFG_PERSONS = "DFG Persons"
|
||||
BACKGROUND_JOBS = "Background Jobs"
|
||||
|
||||
BUND_INSTITUTIONS = "BUND Institutions"
|
||||
|
||||
@@ -1,6 +1,14 @@
|
||||
from enum import StrEnum
|
||||
|
||||
from inse.model import Page
|
||||
from inse.models.openalex.topic import Topic
|
||||
|
||||
|
||||
class TopicSortBy(StrEnum):
|
||||
DISPLAY_NAME = "display_name"
|
||||
WORKS_COUNT = "works_count"
|
||||
CITED_BY_COUNT = "cited_by_count"
|
||||
|
||||
|
||||
class TopicPageV2(Page[Topic]):
|
||||
pass
|
||||
|
||||
@@ -2,10 +2,12 @@ import logging
|
||||
from typing import Annotated
|
||||
|
||||
import inse.topics.v2.service as topics_service
|
||||
from fastapi import APIRouter, Query
|
||||
from fastapi import APIRouter, Path, Query
|
||||
from inse.model import SortDirection
|
||||
from inse.models.openalex.topic import Topic
|
||||
from inse.router_prefixes import RouterPrefixes
|
||||
from inse.tags import Tags
|
||||
from inse.topics.v2.model import TopicPageV2
|
||||
from inse.topics.v2.model import TopicPageV2, TopicSortBy
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -13,6 +15,69 @@ logger = logging.getLogger(__name__)
|
||||
router = APIRouter(prefix=RouterPrefixes.TOPICS_V2, tags=[Tags.TOPICS_V2])
|
||||
|
||||
|
||||
@router.get(
|
||||
"/search",
|
||||
operation_id="searchTopics",
|
||||
summary="Searches for topics based on the provided criteria.",
|
||||
)
|
||||
async def search_topics(
|
||||
search_term: Annotated[
|
||||
str | None,
|
||||
Query(description="The term to search for in topic display names."),
|
||||
] = None,
|
||||
page: Annotated[
|
||||
int,
|
||||
Query(
|
||||
description="The page number to retrieve.",
|
||||
ge=0,
|
||||
),
|
||||
] = 0,
|
||||
size: Annotated[
|
||||
int,
|
||||
Query(
|
||||
description="The number of topics to retrieve per page.",
|
||||
ge=1,
|
||||
le=100,
|
||||
),
|
||||
] = 10,
|
||||
sort_by: Annotated[
|
||||
TopicSortBy,
|
||||
Query(
|
||||
description="The field to sort by.",
|
||||
),
|
||||
] = TopicSortBy.WORKS_COUNT,
|
||||
sort_direction: Annotated[
|
||||
SortDirection,
|
||||
Query(
|
||||
description="The direction to sort.",
|
||||
),
|
||||
] = SortDirection.DESCENDING,
|
||||
) -> TopicPageV2:
|
||||
return await topics_service.search_topics(
|
||||
search_term=search_term,
|
||||
page=page,
|
||||
size=size,
|
||||
sort_by=sort_by,
|
||||
sort_direction=sort_direction,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/single/{raw_oa_topic_id}",
|
||||
operation_id="getTopicById",
|
||||
summary="Returns a topic for a given topic ID.",
|
||||
)
|
||||
async def get_topic_by_id(
|
||||
raw_oa_topic_id: Annotated[
|
||||
str,
|
||||
Path(description="The ID of the topic to retrieve."),
|
||||
],
|
||||
) -> Topic:
|
||||
return await topics_service.get_topic_by_id_or_raise(
|
||||
raw_oa_topic_id=raw_oa_topic_id
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/topics/id",
|
||||
operation_id="getTopicsByIds",
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
|
||||
from inse.exceptions import NotFoundException
|
||||
from inse.integrations import elasticsearch
|
||||
from inse.model import ESIndex
|
||||
from inse.model import ESIndex, SortDirection
|
||||
from inse.models.openalex.topic import Topic
|
||||
from inse.topics.v2.model import TopicPageV2
|
||||
from inse.topics.v2.model import TopicPageV2, TopicSortBy
|
||||
|
||||
|
||||
async def search_topics(
|
||||
async def _search_topics(
|
||||
page: int = 0,
|
||||
size: int = 10,
|
||||
query: dict | None = None,
|
||||
@@ -38,11 +38,80 @@ async def search_topics(
|
||||
|
||||
hits_block = response.get("hits", {})
|
||||
hits = hits_block.get("hits", [])
|
||||
total_hits = hits_block.get("total", {}).get("value", 0)
|
||||
topics: list[Topic] = []
|
||||
for hit in hits:
|
||||
_source = hit.get("_source", {})
|
||||
topics.append(Topic.from_dict(_source)) # type: ignore
|
||||
return TopicPageV2(elements=topics, total=len(topics), page=page, size=size)
|
||||
return TopicPageV2(elements=topics, total=total_hits, page=page, size=size)
|
||||
|
||||
|
||||
async def search_topics(
|
||||
search_term: str | None = None,
|
||||
page: int = 0,
|
||||
size: int = 10,
|
||||
sort_by: TopicSortBy = TopicSortBy.WORKS_COUNT,
|
||||
sort_direction: SortDirection = SortDirection.DESCENDING,
|
||||
) -> TopicPageV2:
|
||||
"""Searches for topics based on a search term.
|
||||
|
||||
Args:
|
||||
search_term (str | None): The term to search for in topic display names. Defaults to None.
|
||||
page (int, optional): The page number to retrieve. Defaults to 0.
|
||||
size (int, optional): The number of topics to retrieve per page. Defaults to 10.
|
||||
sort_by (TopicSortBy, optional): The field to sort by. Defaults to TopicSortBy.WORKS_COUNT.
|
||||
sort_direction (SortDirection, optional): The direction to sort. Defaults to SortDirection.DESCENDING.
|
||||
|
||||
Returns:
|
||||
TopicPageV2: A page of topics matching the search term.
|
||||
"""
|
||||
|
||||
sort = None
|
||||
if sort_by in [TopicSortBy.DISPLAY_NAME]:
|
||||
sort = [{f"{sort_by.value}.keyword": {"order": sort_direction.value}}]
|
||||
else:
|
||||
sort = [{sort_by.value: {"order": sort_direction.value}}]
|
||||
|
||||
query = None
|
||||
if search_term:
|
||||
search_terms = [
|
||||
term.strip() for term in search_term.split(",") if term.strip()
|
||||
]
|
||||
if len(search_terms) == 1:
|
||||
query = {
|
||||
"match_phrase_prefix": {"display_name": search_terms[0]}
|
||||
}
|
||||
elif search_terms:
|
||||
query = {
|
||||
"bool": {
|
||||
"should": [
|
||||
{
|
||||
"match_phrase_prefix": {
|
||||
"display_name": search_term
|
||||
}
|
||||
}
|
||||
for search_term in search_terms
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
|
||||
return await _search_topics(
|
||||
page=page,
|
||||
size=size,
|
||||
query=query,
|
||||
source=[
|
||||
"id",
|
||||
"display_name",
|
||||
"description",
|
||||
"subfield",
|
||||
"field",
|
||||
"domain",
|
||||
"works_count",
|
||||
"cited_by_count",
|
||||
],
|
||||
sort=sort,
|
||||
)
|
||||
|
||||
|
||||
async def autocomplete_topics_for_selector(query: str) -> TopicPageV2:
|
||||
@@ -54,7 +123,7 @@ async def autocomplete_topics_for_selector(query: str) -> TopicPageV2:
|
||||
Returns:
|
||||
TopicPageV2: A page of topics matching the autocomplete criteria.
|
||||
"""
|
||||
return await search_topics(
|
||||
return await _search_topics(
|
||||
page=0,
|
||||
size=10,
|
||||
query={"match_phrase_prefix": {"display_name": query}},
|
||||
@@ -68,6 +137,53 @@ async def autocomplete_topics_for_selector(query: str) -> TopicPageV2:
|
||||
)
|
||||
|
||||
|
||||
async def get_topic_by_id(raw_oa_topic_id: str) -> Topic | None:
|
||||
"""Retrieves a topic based on its ID.
|
||||
|
||||
Args:
|
||||
raw_oa_topic_id (str): The ID of the topic to retrieve.
|
||||
|
||||
Returns:
|
||||
Topic | None: The topic matching the provided ID, or None if not found.
|
||||
"""
|
||||
response = await elasticsearch.get(
|
||||
index=ESIndex.OPENALEX_TOPICS,
|
||||
doc_id=raw_oa_topic_id,
|
||||
source=[
|
||||
"id",
|
||||
"display_name",
|
||||
"description",
|
||||
"subfield",
|
||||
"field",
|
||||
"domain",
|
||||
"works_count",
|
||||
"cited_by_count",
|
||||
],
|
||||
)
|
||||
if response.get("found"):
|
||||
_source = response.get("_source", {})
|
||||
return Topic.from_dict(_source) # type: ignore
|
||||
return None
|
||||
|
||||
|
||||
async def get_topic_by_id_or_raise(raw_oa_topic_id: str) -> Topic:
|
||||
"""Retrieves a topic based on its ID, raising an exception if not found.
|
||||
|
||||
Args:
|
||||
raw_oa_topic_id (str): The ID of the topic to retrieve.
|
||||
|
||||
Raises:
|
||||
NotFoundException: If the topic with the specified ID is not found.
|
||||
|
||||
Returns:
|
||||
Topic: The topic matching the provided ID.
|
||||
"""
|
||||
topic = await get_topic_by_id(raw_oa_topic_id)
|
||||
if topic is None:
|
||||
raise NotFoundException(f"Topic with ID {raw_oa_topic_id} not found.")
|
||||
return topic
|
||||
|
||||
|
||||
async def get_topics_by_ids(topic_ids: list[str]) -> TopicPageV2:
|
||||
"""Retrieves topics based on a list of topic IDs.
|
||||
|
||||
@@ -80,7 +196,7 @@ async def get_topics_by_ids(topic_ids: list[str]) -> TopicPageV2:
|
||||
if not topic_ids:
|
||||
return TopicPageV2(elements=[], total=0, page=0, size=0)
|
||||
|
||||
return await search_topics(
|
||||
return await _search_topics(
|
||||
page=0,
|
||||
size=len(topic_ids),
|
||||
query={"terms": {"id": topic_ids}},
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from inse.topics.v2.service import search_topics
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def anyio_backend():
|
||||
return "asyncio"
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_search_topics_treats_comma_separated_terms_as_alternatives():
|
||||
with patch(
|
||||
"inse.topics.v2.service.elasticsearch.search",
|
||||
new=AsyncMock(
|
||||
return_value={
|
||||
"hits": {"hits": [], "total": {"value": 0}}
|
||||
}
|
||||
),
|
||||
) as search:
|
||||
await search_topics("Artificial Intelligence, Machine Learning")
|
||||
|
||||
assert search.await_args.kwargs["query"] == {
|
||||
"bool": {
|
||||
"should": [
|
||||
{
|
||||
"match_phrase_prefix": {
|
||||
"display_name": "Artificial Intelligence"
|
||||
}
|
||||
},
|
||||
{
|
||||
"match_phrase_prefix": {
|
||||
"display_name": "Machine Learning"
|
||||
}
|
||||
},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
@@ -157,6 +157,32 @@ async def test_get_top_topics_for_entity():
|
||||
assert "items" in res
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_get_top_topics_for_entity_projects():
|
||||
res = await get_top_topics_for_entity(
|
||||
entity_id="https://openalex.org/I62318514",
|
||||
entity_type="institution",
|
||||
start_year=2018,
|
||||
end_year=2022,
|
||||
search_type="projects",
|
||||
)
|
||||
assert isinstance(res, dict)
|
||||
assert "items" in res
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_get_top_topics_for_entity_news():
|
||||
res = await get_top_topics_for_entity(
|
||||
entity_id="UDE",
|
||||
entity_type="institution",
|
||||
start_year=2018,
|
||||
end_year=2024,
|
||||
search_type="news",
|
||||
)
|
||||
assert isinstance(res, dict)
|
||||
assert "items" in res
|
||||
|
||||
|
||||
@pytest.mark.anyio
|
||||
async def test_get_trend_data_delegation():
|
||||
res = await get_trend_data(
|
||||
@@ -165,3 +191,4 @@ async def test_get_trend_data_delegation():
|
||||
)
|
||||
assert res is not None
|
||||
assert len(res.series) > 0
|
||||
|
||||
|
||||
@@ -256,9 +256,6 @@ async def get_top_topics_for_entity(
|
||||
|
||||
if search_type == "projects":
|
||||
try:
|
||||
from inse.patents.search_client import PatentSearchClient
|
||||
patent_client = PatentSearchClient()
|
||||
|
||||
short_id = clean_inst_id(entity_id)
|
||||
full_id = to_full_inst_url(entity_id)
|
||||
|
||||
@@ -296,16 +293,11 @@ async def get_top_topics_for_entity(
|
||||
|
||||
project_ids_by_index: Dict[str, List[str]] = {}
|
||||
|
||||
# 1. BUND - use scan to retrieve all project IDs without 10k limits
|
||||
# 1. BUND - filter by institution/country and date range
|
||||
if include_german:
|
||||
bund_filters = []
|
||||
bund_filters = [TrendQueryBuilder.build_date_range_filter("funding_start", start_year, end_year)]
|
||||
if entity_type == "institution":
|
||||
bund_filters.append({
|
||||
"bool": {
|
||||
"should": [{"match": {"Zuwendungsempfänger": {"query": alias, "operator": "and"}}} for alias in aliases],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
})
|
||||
bund_filters.append(TrendQueryBuilder.build_bund_receiver_clause(aliases))
|
||||
try:
|
||||
p_ids = []
|
||||
async for hit in elasticsearch.scan(
|
||||
@@ -321,7 +313,7 @@ async def get_top_topics_for_entity(
|
||||
except Exception as e:
|
||||
logger.warning("Failed to fetch BUND project IDs in get_top_topics_for_entity: %s", e)
|
||||
|
||||
# 2. DFG - scan institutes & projects
|
||||
# 2. DFG - filter by institute projects and date range
|
||||
if include_german:
|
||||
try:
|
||||
dfg_pids = []
|
||||
@@ -338,7 +330,7 @@ async def get_top_topics_for_entity(
|
||||
dfg_pids.append(str(p["project_id"]))
|
||||
|
||||
if dfg_pids or entity_type != "institution":
|
||||
dfg_filters = []
|
||||
dfg_filters = [TrendQueryBuilder.build_date_range_filter("funding_start", start_year, end_year)]
|
||||
if dfg_pids:
|
||||
dfg_filters.append({"ids": {"values": dfg_pids}})
|
||||
|
||||
@@ -357,7 +349,7 @@ async def get_top_topics_for_entity(
|
||||
except Exception as e:
|
||||
logger.warning("Failed to fetch DFG project IDs in get_top_topics_for_entity: %s", e)
|
||||
|
||||
# 3. EU CORDIS
|
||||
# 3. EU CORDIS - filter orgs and verify project start dates
|
||||
eu_indices = [
|
||||
(ESIndex.CORDIS_EU_HORIZON_EUROPE_ORGANIZATIONS, ESIndex.CORDIS_EU_HORIZON_EUROPE_PROJECTS, ESIndex.PROJECTS_CORDIS_EU_HEUROPE_TOPICS.value),
|
||||
(ESIndex.CORDIS_EU_HORIZON_2020_ORGANIZATIONS, ESIndex.CORDIS_EU_HORIZON_2020_PROJECTS, ESIndex.PROJECTS_CORDIS_EU_H2020_TOPICS.value),
|
||||
@@ -371,18 +363,35 @@ async def get_top_topics_for_entity(
|
||||
elif entity_type == "country":
|
||||
filter_clauses.append({"term": {"country": entity_id.strip().upper()}})
|
||||
|
||||
eu_org_res = await patent_client._search(
|
||||
eu_org_res = await elasticsearch.search(
|
||||
index=org_idx.value,
|
||||
payload={
|
||||
body={
|
||||
"query": {"bool": {"filter": filter_clauses}},
|
||||
"size": 0,
|
||||
"_source": False,
|
||||
"aggs": {"project_ids": {"terms": {"field": "projectID", "size": 65536}}},
|
||||
},
|
||||
cluster=ESCluster.INSE,
|
||||
)
|
||||
eu_pids = [b["key"] for b in eu_org_res.get("aggregations", {}).get("project_ids", {}).get("buckets", [])]
|
||||
if eu_pids:
|
||||
project_ids_by_index[topic_idx] = eu_pids
|
||||
raw_eu_pids = [b["key"] for b in eu_org_res.get("aggregations", {}).get("project_ids", {}).get("buckets", [])]
|
||||
if raw_eu_pids:
|
||||
# Filter project IDs by start date range
|
||||
dated_eu_pids = []
|
||||
proj_date_filter = [
|
||||
{"terms": {"id": raw_eu_pids}},
|
||||
TrendQueryBuilder.build_date_range_filter("startDate", start_year, end_year),
|
||||
]
|
||||
async for hit in elasticsearch.scan(
|
||||
index=proj_idx.value,
|
||||
query={"bool": {"filter": proj_date_filter}},
|
||||
source=["id"],
|
||||
cluster=ESCluster.INSE,
|
||||
):
|
||||
pid = hit.get("_source", {}).get("id") or hit.get("_id")
|
||||
if pid:
|
||||
dated_eu_pids.append(str(pid))
|
||||
if dated_eu_pids:
|
||||
project_ids_by_index[topic_idx] = dated_eu_pids
|
||||
except Exception as e:
|
||||
logger.warning("Failed to fetch EU project IDs for %s: %s", org_idx.value, e)
|
||||
|
||||
@@ -447,31 +456,99 @@ async def get_top_topics_for_entity(
|
||||
|
||||
if search_type == "news":
|
||||
try:
|
||||
res = await elasticsearch.search(
|
||||
index="aktuell_postproc",
|
||||
body={
|
||||
"query": {"match_all": {}},
|
||||
"size": 0,
|
||||
"_source": False,
|
||||
"aggs": {
|
||||
"top_topics": {
|
||||
"terms": {
|
||||
"field": "topics.display_name.keyword",
|
||||
"size": DEFAULT_TOP_TOPICS_SIZE,
|
||||
date_filter = TrendQueryBuilder.build_date_range_filter("date_year", start_year, end_year)
|
||||
news_ids = []
|
||||
try:
|
||||
async for hit in elasticsearch.scan(
|
||||
index=ESIndex.AKTUELLES.value,
|
||||
query={"bool": {"filter": [date_filter]}},
|
||||
source=["news_id"],
|
||||
cluster=ESCluster.INSE,
|
||||
):
|
||||
nid = hit.get("_id") or hit.get("_source", {}).get("news_id")
|
||||
if nid:
|
||||
news_ids.append(str(nid))
|
||||
except Exception as e:
|
||||
logger.warning("Failed scanning aktuell for news IDs in date range: %s", e)
|
||||
|
||||
topic_counts: Dict[str, int] = {}
|
||||
if news_ids:
|
||||
msearch_queries = []
|
||||
for i in range(0, len(news_ids), 2000):
|
||||
chunk = news_ids[i : i + 2000]
|
||||
payload = {
|
||||
"query": {
|
||||
"bool": {
|
||||
"should": [
|
||||
{"ids": {"values": chunk}},
|
||||
{"terms": {"news_id.keyword": chunk}},
|
||||
{"terms": {"news_id": chunk}},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
cluster=ESCluster.INSE,
|
||||
)
|
||||
buckets = res.get("aggregations", {}).get("top_topics", {}).get("buckets", [])
|
||||
items = [{"name": b["key"], "count": b["doc_count"]} for b in buckets]
|
||||
total_hits = res.get("hits", {}).get("total", {})
|
||||
total_val = total_hits.get("value", 0) if isinstance(total_hits, dict) else int(total_hits or 0)
|
||||
sum_top = sum(b["count"] for b in items)
|
||||
other_count = max(0, total_val - sum_top)
|
||||
},
|
||||
"size": 0,
|
||||
"_source": False,
|
||||
"aggs": {
|
||||
"top_topics": {
|
||||
"terms": {
|
||||
"field": "topic_matches.topic_display_name.keyword",
|
||||
"size": 100,
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
msearch_queries.append((ESIndex.AKTUELLES_OPENALEX_TOPICS.value, payload))
|
||||
|
||||
if msearch_queries:
|
||||
try:
|
||||
responses = await elasticsearch.msearch(msearch_queries, cluster=ESCluster.INSE)
|
||||
for res in responses:
|
||||
buckets = res.get("aggregations", {}).get("top_topics", {}).get("buckets", [])
|
||||
for b in buckets:
|
||||
t_name = b["key"]
|
||||
cnt = b["doc_count"]
|
||||
topic_counts[t_name] = topic_counts.get(t_name, 0) + cnt
|
||||
except Exception as e:
|
||||
logger.warning("Failed to aggregate news top topics via msearch: %s", e)
|
||||
else:
|
||||
# If no year filter bounds active or scan returned no IDs, aggregate all topics directly from openalex_topics
|
||||
try:
|
||||
res = await elasticsearch.search(
|
||||
index=ESIndex.AKTUELLES_OPENALEX_TOPICS.value,
|
||||
body={
|
||||
"query": {"match_all": {}},
|
||||
"size": 0,
|
||||
"_source": False,
|
||||
"aggs": {
|
||||
"top_topics": {
|
||||
"terms": {
|
||||
"field": "topic_matches.topic_display_name.keyword",
|
||||
"size": 100,
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
cluster=ESCluster.INSE,
|
||||
)
|
||||
buckets = res.get("aggregations", {}).get("top_topics", {}).get("buckets", [])
|
||||
for b in buckets:
|
||||
t_name = b["key"]
|
||||
cnt = b["doc_count"]
|
||||
topic_counts[t_name] = topic_counts.get(t_name, 0) + cnt
|
||||
except Exception as e:
|
||||
logger.warning("Failed to fallback query news top topics: %s", e)
|
||||
|
||||
sorted_topics = sorted(topic_counts.items(), key=lambda x: x[1], reverse=True)
|
||||
top_slice = sorted_topics[:DEFAULT_TOP_TOPICS_SIZE]
|
||||
items = [{"name": name, "count": count} for name, count in top_slice]
|
||||
|
||||
sum_top = sum(count for name, count in top_slice)
|
||||
total_topics = sum(topic_counts.values())
|
||||
other_count = max(0, total_topics - sum_top)
|
||||
if other_count > 0:
|
||||
items.append({"name": "Andere Themen", "count": other_count})
|
||||
|
||||
return {"items": items}
|
||||
except Exception as e:
|
||||
logger.error("Failed to query top news topics for entity: %s", e)
|
||||
|
||||
@@ -146,7 +146,7 @@ class TrendMetadataResolver:
|
||||
return topic_ids
|
||||
try:
|
||||
res = await elasticsearch.search(
|
||||
index="openalex-topics",
|
||||
index=ESIndex.OPENALEX_TOPICS.value,
|
||||
query={"bool": {"should": [{"match_phrase": {"display_name": t}} for t in topic_names]}},
|
||||
size=len(topic_names) * 2,
|
||||
source=["id", "display_name"],
|
||||
@@ -305,3 +305,90 @@ class TrendQueryBuilder:
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def build_bund_keyword_query(keyword: str) -> Dict[str, Any]:
|
||||
"""Builds keyword filter clause for BUND projects."""
|
||||
return {
|
||||
"bool": {
|
||||
"should": [{"match": {field: keyword}} for field in BUND_PROJECT_TEXT_FIELDS],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def build_dfg_keyword_query(keyword: str) -> Dict[str, Any]:
|
||||
"""Builds keyword filter clause for DFG projects."""
|
||||
return {
|
||||
"bool": {
|
||||
"should": [
|
||||
{"match": {field: keyword}} for field in DFG_PROJECT_TEXT_FIELDS
|
||||
] + [
|
||||
{"nested": {"path": "publications", "query": {"match": {"publications.title": keyword}}}},
|
||||
{
|
||||
"nested": {
|
||||
"path": "subject_classification",
|
||||
"query": {
|
||||
"bool": {
|
||||
"should": [
|
||||
{"match": {"subject_classification.fach": keyword}},
|
||||
{"match": {"subject_classification.fachkollegium": keyword}},
|
||||
{"match": {"subject_classification.wissenschaftsbereich": keyword}},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def build_cordis_keyword_query(keyword: str) -> Dict[str, Any]:
|
||||
"""Builds keyword filter clause for EU CORDIS projects."""
|
||||
return {
|
||||
"bool": {
|
||||
"should": [{"match": {field: keyword}} for field in CORDIS_PROJECT_TEXT_FIELDS],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def build_bund_receiver_clause(aliases: List[str]) -> Dict[str, Any]:
|
||||
"""Builds Zuwendungsempfänger matching clause for BUND projects."""
|
||||
return {
|
||||
"bool": {
|
||||
"should": [
|
||||
{"match": {BUND_RECEIVER_FIELD: {"query": alias, "operator": "and"}}}
|
||||
for alias in aliases
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
BUND_RECEIVER_FIELD = "Zuwendungsempfänger"
|
||||
BUND_PROJECT_TEXT_FIELDS = [
|
||||
"Thema",
|
||||
"Klartext Leistungsplansystematik",
|
||||
"Förderprofil",
|
||||
"Leistungsplansystematik_fullname",
|
||||
]
|
||||
|
||||
DFG_PROJECT_TEXT_FIELDS = [
|
||||
"title_de",
|
||||
"title_en",
|
||||
"description",
|
||||
"subject_area_de",
|
||||
"subject_area_en",
|
||||
"abstract_de",
|
||||
"abstract_en",
|
||||
"final_report_abstract_de",
|
||||
"final_report_abstract_en",
|
||||
]
|
||||
|
||||
CORDIS_PROJECT_TEXT_FIELDS = ["title", "objective"]
|
||||
AKTUELLES_SEARCH_FIELDS = ["main_content", "full_content", "maintitle", "subtitle", "intro_content"]
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ from .model import (
|
||||
from .trend_query_builder import (
|
||||
DEFAULT_INSTITUTION_ID,
|
||||
DEFAULT_INSTITUTION_NAME,
|
||||
AKTUELLES_SEARCH_FIELDS,
|
||||
TrendMetadataResolver,
|
||||
TrendQueryBuilder,
|
||||
clean_inst_id,
|
||||
@@ -573,8 +574,8 @@ class PatentsTrendStrategy(TrendStrategy):
|
||||
"aggs": {"by_year": {"terms": {"field": "date_publication_year", "size": 100}}},
|
||||
}
|
||||
|
||||
msearch_queries.append(("uspto_patents_3.0", uspto_query))
|
||||
msearch_queries.append(("epo_index_1.0", epo_query))
|
||||
msearch_queries.append((ESIndex.USPTO_INDEX.value, uspto_query))
|
||||
msearch_queries.append((ESIndex.EPO_INDEX.value, epo_query))
|
||||
topic_search_indices.append(t)
|
||||
|
||||
if msearch_queries:
|
||||
@@ -693,9 +694,6 @@ class ProjectsTrendStrategy(TrendStrategy):
|
||||
if not filters_map:
|
||||
return TrendResponse(series=[], years=years_range, location_mappings=location_mappings)
|
||||
|
||||
from inse.patents.search_client import PatentSearchClient
|
||||
patent_client = PatentSearchClient()
|
||||
|
||||
# Resolve DFG project IDs for institutions via scan/search without size limit cutoffs
|
||||
dfg_institution_projects: Dict[str, List[str]] = {}
|
||||
|
||||
@@ -775,7 +773,29 @@ class ProjectsTrendStrategy(TrendStrategy):
|
||||
for key in filters_map
|
||||
}
|
||||
|
||||
async def query_project_trends(entity_key: str, entity_type: str, entity_val: Any, topic: str, keyword: str):
|
||||
# Batch all project queries into single msearch request
|
||||
msearch_queries = []
|
||||
meta_indices: List[Tuple[str, str, str]] = [] # (entity_key, topic, agg_type)
|
||||
|
||||
async def prepare_project_trend_queries(entity_key: str, entity_type: str, entity_val: Any, topic: str, keyword: str):
|
||||
eu_indices = [
|
||||
(
|
||||
ESIndex.CORDIS_EU_HORIZON_EUROPE_ORGANIZATIONS,
|
||||
ESIndex.CORDIS_EU_HORIZON_EUROPE_PROJECTS,
|
||||
ESIndex.PROJECTS_CORDIS_EU_HEUROPE_TOPICS.value,
|
||||
),
|
||||
(
|
||||
ESIndex.CORDIS_EU_HORIZON_2020_ORGANIZATIONS,
|
||||
ESIndex.CORDIS_EU_HORIZON_2020_PROJECTS,
|
||||
ESIndex.PROJECTS_CORDIS_EU_H2020_TOPICS.value,
|
||||
),
|
||||
(
|
||||
ESIndex.CORDIS_EU_FP7_ORGANIZATIONS,
|
||||
ESIndex.CORDIS_EU_FP7_PROJECTS,
|
||||
ESIndex.PROJECTS_CORDIS_EU_FP7_TOPICS_MAPPING.value,
|
||||
),
|
||||
]
|
||||
|
||||
async def get_eu_entity_project_ids(org_index: ESIndex) -> List[str]:
|
||||
filter_clauses = []
|
||||
if entity_type == "institution":
|
||||
@@ -787,14 +807,15 @@ class ProjectsTrendStrategy(TrendStrategy):
|
||||
filter_clauses.append({"terms": {"country": entity_val}})
|
||||
|
||||
try:
|
||||
res = await patent_client._search(
|
||||
res = await elasticsearch.search(
|
||||
index=org_index.value,
|
||||
payload={
|
||||
body={
|
||||
"query": {"bool": {"filter": filter_clauses}},
|
||||
"size": 0,
|
||||
"_source": False,
|
||||
"aggs": {"project_ids": {"terms": {"field": "projectID", "size": 65536}}},
|
||||
},
|
||||
cluster=ESCluster.INSE,
|
||||
)
|
||||
buckets = res.get("aggregations", {}).get("project_ids", {}).get("buckets", [])
|
||||
return [b["key"] for b in buckets]
|
||||
@@ -802,26 +823,7 @@ class ProjectsTrendStrategy(TrendStrategy):
|
||||
logger.warning("Failed to query CORDIS orgs index %s: %s", org_index.value, e)
|
||||
return []
|
||||
|
||||
eu_indices = [
|
||||
(
|
||||
ESIndex.CORDIS_EU_HORIZON_EUROPE_ORGANIZATIONS,
|
||||
ESIndex.CORDIS_EU_HORIZON_EUROPE_PROJECTS,
|
||||
"projects_cordiseu_heurope_openalex_topics",
|
||||
),
|
||||
(
|
||||
ESIndex.CORDIS_EU_HORIZON_2020_ORGANIZATIONS,
|
||||
ESIndex.CORDIS_EU_HORIZON_2020_PROJECTS,
|
||||
"projects_cordiseu_h2020_openalex_topics",
|
||||
),
|
||||
(
|
||||
ESIndex.CORDIS_EU_FP7_ORGANIZATIONS,
|
||||
ESIndex.CORDIS_EU_FP7_PROJECTS,
|
||||
"projects_cordiseu_fp7_openalex_topics",
|
||||
),
|
||||
]
|
||||
|
||||
eu_org_ids_list = await asyncio.gather(*(get_eu_entity_project_ids(org_idx) for org_idx, _, _ in eu_indices))
|
||||
actual_tasks = []
|
||||
|
||||
# BUND
|
||||
include_bund = True
|
||||
@@ -834,15 +836,10 @@ class ProjectsTrendStrategy(TrendStrategy):
|
||||
bund_filters = []
|
||||
if entity_type == "institution":
|
||||
aliases = resolved_aliases.get(entity_val, [])
|
||||
bund_filters.append({
|
||||
"bool": {
|
||||
"should": [{"match": {"Zuwendungsempfänger": {"query": alias, "operator": "and"}}} for alias in aliases],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
})
|
||||
bund_filters.append(TrendQueryBuilder.build_bund_receiver_clause(aliases))
|
||||
|
||||
if fuzzy:
|
||||
p_ids = topic_project_ids[topic].get("projects_bund_openalex_topics", [])
|
||||
p_ids = topic_project_ids[topic].get(ESIndex.PROJECTS_BUND_TOPICS.value, [])
|
||||
if p_ids:
|
||||
bund_filters.append({"ids": {"values": p_ids}})
|
||||
bund_query = {"query": {"bool": {"filter": bund_filters}}}
|
||||
@@ -852,19 +849,7 @@ class ProjectsTrendStrategy(TrendStrategy):
|
||||
bund_query = {
|
||||
"query": {
|
||||
"bool": {
|
||||
"filter": [
|
||||
{
|
||||
"bool": {
|
||||
"should": [
|
||||
{"match": {"Thema": keyword}},
|
||||
{"match": {"Klartext Leistungsplansystematik": keyword}},
|
||||
{"match": {"Förderprofil": keyword}},
|
||||
{"match": {"Leistungsplansystematik_fullname": keyword}},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
}
|
||||
] + bund_filters
|
||||
"filter": [TrendQueryBuilder.build_bund_keyword_query(keyword)] + bund_filters
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -884,16 +869,8 @@ class ProjectsTrendStrategy(TrendStrategy):
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
async def process_bund():
|
||||
try:
|
||||
res = await patent_client._search(index=ESIndex.PROJECTS_BUND_V1.value, payload=bund_payload)
|
||||
return "date", res.get("aggregations", {}).get("projects_by_year", {}).get("buckets", [])
|
||||
except Exception as e:
|
||||
logger.warning("Failed to query BUND projects: %s", e)
|
||||
return "date", []
|
||||
|
||||
actual_tasks.append(process_bund())
|
||||
msearch_queries.append((ESIndex.PROJECTS_BUND_V1.value, bund_payload))
|
||||
meta_indices.append((entity_key, topic, "date"))
|
||||
|
||||
# DFG
|
||||
include_dfg = True
|
||||
@@ -927,39 +904,7 @@ class ProjectsTrendStrategy(TrendStrategy):
|
||||
else:
|
||||
if dfg_inst_pids is not None:
|
||||
dfg_filters.append({"ids": {"values": dfg_inst_pids}})
|
||||
|
||||
dfg_filters.append({
|
||||
"bool": {
|
||||
"should": [
|
||||
{"match": {"title_de": keyword}},
|
||||
{"match": {"title_en": keyword}},
|
||||
{"match": {"description": keyword}},
|
||||
{"match": {"subject_area_de": keyword}},
|
||||
{"match": {"subject_area_en": keyword}},
|
||||
{"match": {"abstract_de": keyword}},
|
||||
{"match": {"abstract_en": keyword}},
|
||||
{"match": {"final_report_abstract_de": keyword}},
|
||||
{"match": {"final_report_abstract_en": keyword}},
|
||||
{"nested": {"path": "publications", "query": {"match": {"publications.title": keyword}}}},
|
||||
{
|
||||
"nested": {
|
||||
"path": "subject_classification",
|
||||
"query": {
|
||||
"bool": {
|
||||
"should": [
|
||||
{"match": {"subject_classification.fach": keyword}},
|
||||
{"match": {"subject_classification.fachkollegium": keyword}},
|
||||
{"match": {"subject_classification.wissenschaftsbereich": keyword}},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
})
|
||||
dfg_filters.append(TrendQueryBuilder.build_dfg_keyword_query(keyword))
|
||||
|
||||
if include_dfg:
|
||||
dfg_payload = {
|
||||
@@ -968,18 +913,10 @@ class ProjectsTrendStrategy(TrendStrategy):
|
||||
"_source": False,
|
||||
"aggs": {"projects_by_year": {"terms": {"field": "funding_start", "size": 100}}},
|
||||
}
|
||||
msearch_queries.append((ESIndex.DFG_PROJECTS.value, dfg_payload))
|
||||
meta_indices.append((entity_key, topic, "terms"))
|
||||
|
||||
async def process_dfg():
|
||||
try:
|
||||
res = await patent_client._search(index=ESIndex.DFG_PROJECTS.value, payload=dfg_payload)
|
||||
return "terms", res.get("aggregations", {}).get("projects_by_year", {}).get("buckets", [])
|
||||
except Exception as e:
|
||||
logger.warning("Failed to query DFG projects: %s", e)
|
||||
return "terms", []
|
||||
|
||||
actual_tasks.append(process_dfg())
|
||||
|
||||
# EU Cordis
|
||||
# EU CORDIS
|
||||
for eu_idx, (org_index, proj_index, mapping_key) in enumerate(eu_indices):
|
||||
entity_project_ids = eu_org_ids_list[eu_idx]
|
||||
if not entity_project_ids:
|
||||
@@ -998,12 +935,7 @@ class ProjectsTrendStrategy(TrendStrategy):
|
||||
"bool": {
|
||||
"filter": [
|
||||
{"terms": {"id": entity_project_ids}},
|
||||
{
|
||||
"bool": {
|
||||
"should": [{"match": {"title": keyword}}, {"match": {"objective": keyword}}],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
},
|
||||
TrendQueryBuilder.build_cordis_keyword_query(keyword),
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -1024,53 +956,46 @@ class ProjectsTrendStrategy(TrendStrategy):
|
||||
}
|
||||
},
|
||||
}
|
||||
msearch_queries.append((proj_index.value, proj_payload))
|
||||
meta_indices.append((entity_key, topic, "date"))
|
||||
|
||||
async def process_cordis(p_idx=proj_index, payload=proj_payload):
|
||||
try:
|
||||
res = await patent_client._search(index=p_idx.value, payload=payload)
|
||||
return "date", res.get("aggregations", {}).get("projects_by_year", {}).get("buckets", [])
|
||||
except Exception as e:
|
||||
logger.warning("Failed to query CORDIS projects index %s: %s", p_idx.value, e)
|
||||
return "date", []
|
||||
|
||||
actual_tasks.append(process_cordis())
|
||||
|
||||
if not actual_tasks:
|
||||
return
|
||||
|
||||
results = await asyncio.gather(*actual_tasks)
|
||||
year_counts: Dict[int, int] = {}
|
||||
for agg_type, buckets in results:
|
||||
for b in buckets:
|
||||
if agg_type == "date":
|
||||
yr_str = b.get("key_as_string") or str(b.get("key", ""))
|
||||
if yr_str:
|
||||
try:
|
||||
yr = int(yr_str[:4])
|
||||
if start_year <= yr <= end_year:
|
||||
year_counts[yr] = year_counts.get(yr, 0) + b.get("doc_count", 0)
|
||||
except ValueError:
|
||||
pass
|
||||
else:
|
||||
yr_val = b.get("key")
|
||||
if yr_val is not None:
|
||||
try:
|
||||
yr = int(str(yr_val)[:4])
|
||||
if start_year <= yr <= end_year:
|
||||
year_counts[yr] = year_counts.get(yr, 0) + b.get("doc_count", 0)
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
for yr, count in year_counts.items():
|
||||
accumulated_data[entity_key][topic][yr] = (count, 1)
|
||||
|
||||
tasks = []
|
||||
prep_tasks = []
|
||||
for entity_key, (entity_type, entity_val) in filters_map.items():
|
||||
for idx, topic in enumerate(topics):
|
||||
keyword = keywords[idx] if (keywords and idx < len(keywords)) else topic
|
||||
tasks.append(query_project_trends(entity_key, entity_type, entity_val, topic, keyword))
|
||||
prep_tasks.append(prepare_project_trend_queries(entity_key, entity_type, entity_val, topic, keyword))
|
||||
|
||||
await asyncio.gather(*tasks)
|
||||
await asyncio.gather(*prep_tasks)
|
||||
|
||||
if msearch_queries:
|
||||
try:
|
||||
responses = await elasticsearch.msearch(msearch_queries, cluster=ESCluster.INSE)
|
||||
for idx, res in enumerate(responses):
|
||||
entity_key, topic, agg_type = meta_indices[idx]
|
||||
buckets = res.get("aggregations", {}).get("projects_by_year", {}).get("buckets", [])
|
||||
for b in buckets:
|
||||
if agg_type == "date":
|
||||
yr_str = b.get("key_as_string") or str(b.get("key", ""))
|
||||
if yr_str:
|
||||
try:
|
||||
yr = int(yr_str[:4])
|
||||
if start_year <= yr <= end_year:
|
||||
c_cnt, _ = accumulated_data[entity_key][topic][yr]
|
||||
accumulated_data[entity_key][topic][yr] = (c_cnt + b.get("doc_count", 0), 1)
|
||||
except ValueError:
|
||||
pass
|
||||
else:
|
||||
yr_val = b.get("key")
|
||||
if yr_val is not None:
|
||||
try:
|
||||
yr = int(str(yr_val)[:4])
|
||||
if start_year <= yr <= end_year:
|
||||
c_cnt, _ = accumulated_data[entity_key][topic][yr]
|
||||
accumulated_data[entity_key][topic][yr] = (c_cnt + b.get("doc_count", 0), 1)
|
||||
except ValueError:
|
||||
pass
|
||||
except Exception as e:
|
||||
logger.error("Failed to execute msearch for project trends: %s", e)
|
||||
|
||||
normalized_lookup = self._normalize_series(years_range, accumulated_data, topics)
|
||||
|
||||
@@ -1139,14 +1064,26 @@ class NewsTrendStrategy(TrendStrategy):
|
||||
for t in topics
|
||||
}
|
||||
|
||||
AKTUELLES_SEARCH_FIELDS = ["main_content", "full_content", "maintitle", "subtitle", "intro_content"]
|
||||
STOP_WORDS = {"in", "and", "or", "und", "oder", "der", "die", "das", "von", "mit", "zu", "at", "by", "on", "for", "to", "a", "an", "the"}
|
||||
|
||||
# Scan UDE news postprocessed index to get matching news IDs without size limit cutoffs
|
||||
# Scan UDE news OpenAlex topics index to get matching news IDs without size limit cutoffs
|
||||
async def fetch_news_ids_for_term(idx: int, t_name: str) -> List[str]:
|
||||
news_ids: Set[str] = set()
|
||||
if fuzzy:
|
||||
term = t_name
|
||||
es_query = {"match": {"topics.display_name": term}}
|
||||
es_query = {"term": {"topic_matches.topic_display_name.keyword": term}}
|
||||
try:
|
||||
async for hit in elasticsearch.scan(
|
||||
index=ESIndex.AKTUELLES_OPENALEX_TOPICS.value,
|
||||
query=es_query,
|
||||
source=["news_id"],
|
||||
cluster=ESCluster.INSE,
|
||||
):
|
||||
nid = hit.get("_source", {}).get("news_id") or hit.get("_id")
|
||||
if nid:
|
||||
news_ids.add(str(nid))
|
||||
except Exception as e:
|
||||
logger.warning("Failed to scan UDE news OpenAlex topics index %s: %s", ESIndex.AKTUELLES_OPENALEX_TOPICS.value, e)
|
||||
else:
|
||||
if keywords and idx < len(keywords) and keywords[idx]:
|
||||
raw_kw = keywords[idx]
|
||||
@@ -1155,43 +1092,28 @@ class NewsTrendStrategy(TrendStrategy):
|
||||
term = t_name
|
||||
else:
|
||||
term = t_name
|
||||
es_query = {"match": {"keywords": term}}
|
||||
|
||||
news_ids: Set[str] = set()
|
||||
try:
|
||||
async for hit in elasticsearch.scan(
|
||||
index="aktuell_postproc",
|
||||
query=es_query,
|
||||
source=["news_id"],
|
||||
cluster=ESCluster.INSE,
|
||||
):
|
||||
nid = hit.get("_source", {}).get("news_id")
|
||||
if nid:
|
||||
news_ids.add(nid)
|
||||
except Exception as e:
|
||||
logger.warning("Failed to scan UDE news postproc: %s", e)
|
||||
|
||||
# If non-fuzzy keyword search, also search article content fields in 'aktuell' index
|
||||
if not fuzzy and term and term.lower() not in STOP_WORDS and len(term.strip()) > 1:
|
||||
try:
|
||||
content_query = {
|
||||
"query_string": {
|
||||
"query": term,
|
||||
"fields": AKTUELLES_SEARCH_FIELDS,
|
||||
"default_operator": "AND",
|
||||
# If non-fuzzy keyword search, search article content fields in 'aktuell' index
|
||||
if term and term.lower() not in STOP_WORDS and len(term.strip()) > 1:
|
||||
try:
|
||||
content_query = {
|
||||
"query_string": {
|
||||
"query": term,
|
||||
"fields": AKTUELLES_SEARCH_FIELDS,
|
||||
"default_operator": "AND",
|
||||
}
|
||||
}
|
||||
}
|
||||
async for hit in elasticsearch.scan(
|
||||
index="aktuell",
|
||||
query=content_query,
|
||||
source=["news_id"],
|
||||
cluster=ESCluster.INSE,
|
||||
):
|
||||
nid = hit.get("_id") or hit.get("_source", {}).get("news_id")
|
||||
if nid:
|
||||
news_ids.add(nid)
|
||||
except Exception as e:
|
||||
logger.warning("Failed to scan UDE news content in aktuell: %s", e)
|
||||
async for hit in elasticsearch.scan(
|
||||
index=ESIndex.AKTUELLES.value,
|
||||
query=content_query,
|
||||
source=["news_id"],
|
||||
cluster=ESCluster.INSE,
|
||||
):
|
||||
nid = hit.get("_id") or hit.get("_source", {}).get("news_id")
|
||||
if nid:
|
||||
news_ids.add(str(nid))
|
||||
except Exception as e:
|
||||
logger.warning("Failed to scan UDE news content in aktuell: %s", e)
|
||||
|
||||
return list(news_ids)
|
||||
|
||||
@@ -1210,7 +1132,16 @@ class NewsTrendStrategy(TrendStrategy):
|
||||
"query": {
|
||||
"bool": {
|
||||
"filter": [
|
||||
{"ids": {"values": chunk}},
|
||||
{
|
||||
"bool": {
|
||||
"should": [
|
||||
{"ids": {"values": chunk}},
|
||||
{"terms": {"news_id.keyword": chunk}},
|
||||
{"terms": {"news_id": chunk}},
|
||||
],
|
||||
"minimum_should_match": 1,
|
||||
}
|
||||
},
|
||||
TrendQueryBuilder.build_date_range_filter("date_year", start_year, end_year),
|
||||
]
|
||||
}
|
||||
@@ -1219,7 +1150,7 @@ class NewsTrendStrategy(TrendStrategy):
|
||||
"size": 0,
|
||||
"_source": False,
|
||||
}
|
||||
chunk_queries.append(("aktuell", q_body))
|
||||
chunk_queries.append((ESIndex.AKTUELLES.value, q_body))
|
||||
|
||||
if chunk_queries:
|
||||
try:
|
||||
|
||||
@@ -22,6 +22,68 @@ logger = logging.getLogger(__name__)
|
||||
router = APIRouter(prefix=RouterPrefixes.WORKS_V2, tags=[Tags.WORKS_V2])
|
||||
|
||||
|
||||
@router.get(
|
||||
"/search",
|
||||
operation_id="searchWorks",
|
||||
summary="Search works with filters.",
|
||||
)
|
||||
async def search_works(
|
||||
page: Annotated[
|
||||
int, Query(description="The page number to retrieve. (0-based)", ge=0)
|
||||
] = 0,
|
||||
size: Annotated[
|
||||
int,
|
||||
Query(description="The number of works to retrieve per page.", ge=1, le=100),
|
||||
] = 10,
|
||||
title: Annotated[
|
||||
str, Query(description="A title to filter by (partial matches allowed).")
|
||||
] = "",
|
||||
publication_years: Annotated[
|
||||
list[int] | None,
|
||||
Query(description="A list of publication years to filter by."),
|
||||
] = None,
|
||||
publication_types: Annotated[
|
||||
list[str] | None,
|
||||
Query(description="A list of publication types to filter by."),
|
||||
] = None,
|
||||
author_ids: Annotated[
|
||||
list[str] | None,
|
||||
Query(description="A list of author IDs to filter by."),
|
||||
] = None,
|
||||
institution_ids: Annotated[
|
||||
list[str] | None,
|
||||
Query(description="A list of institution IDs to filter by."),
|
||||
] = None,
|
||||
topic_ids: Annotated[
|
||||
list[str] | None,
|
||||
Query(description="A list of topic IDs to filter by."),
|
||||
] = None,
|
||||
language_codes: Annotated[
|
||||
list[str] | None,
|
||||
Query(description="A list of language codes to filter by."),
|
||||
] = None,
|
||||
sort_by: Annotated[
|
||||
WorkSortBy, Query(description="The field to sort by.")
|
||||
] = WorkSortBy.PUBLICATION_YEAR,
|
||||
sort_order: Annotated[
|
||||
SortDirection, Query(description="The order to sort by.")
|
||||
] = SortDirection.DESCENDING,
|
||||
) -> WorkPageV2:
|
||||
return await works_service.search_works(
|
||||
page=page,
|
||||
size=size,
|
||||
title=title,
|
||||
publication_years=publication_years or [],
|
||||
publication_types=publication_types or [],
|
||||
author_ids=author_ids or [],
|
||||
institution_ids=institution_ids or [],
|
||||
topic_ids=topic_ids or [],
|
||||
language_codes=language_codes or [],
|
||||
sort_by=sort_by,
|
||||
sort_order=sort_order,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/author/{raw_oa_author_id}",
|
||||
operation_id="getAuthorWorkPage",
|
||||
@@ -218,6 +280,65 @@ async def get_institution_works(
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/topic/{raw_oa_topic_id}",
|
||||
operation_id="getTopicWorkPage",
|
||||
summary="Returns a paginated list of works for a given topic based on its ID.",
|
||||
)
|
||||
async def get_topic_works(
|
||||
raw_oa_topic_id: Annotated[str, Path(description="The raw OpenAlex topic id.")],
|
||||
page: Annotated[
|
||||
int, Query(description="The page number to retrieve. (0-based)", ge=0)
|
||||
] = 0,
|
||||
size: Annotated[
|
||||
int,
|
||||
Query(description="The number of works to retrieve per page.", ge=1, le=100),
|
||||
] = 10,
|
||||
title: Annotated[
|
||||
str, Query(description="A title to filter by (partial matches allowed).")
|
||||
] = "",
|
||||
publication_years: Annotated[
|
||||
list[int] | None,
|
||||
Query(description="A list of publication years to filter by."),
|
||||
] = None,
|
||||
publication_types: Annotated[
|
||||
list[str] | None,
|
||||
Query(description="A list of publication types to filter by."),
|
||||
] = None,
|
||||
author_ids: Annotated[
|
||||
list[str] | None,
|
||||
Query(description="A list of author IDs to filter by."),
|
||||
] = None,
|
||||
institution_ids: Annotated[
|
||||
list[str] | None,
|
||||
Query(description="A list of institution IDs to filter by."),
|
||||
] = None,
|
||||
language_codes: Annotated[
|
||||
list[str] | None,
|
||||
Query(description="A list of language codes to filter by."),
|
||||
] = None,
|
||||
sort_by: Annotated[
|
||||
WorkSortBy, Query(description="The field to sort by.")
|
||||
] = WorkSortBy.PUBLICATION_YEAR,
|
||||
sort_order: Annotated[
|
||||
SortDirection, Query(description="The order to sort by.")
|
||||
] = SortDirection.DESCENDING,
|
||||
) -> WorkPageV2:
|
||||
return await works_service.get_topic_works(
|
||||
raw_oa_topic_id=raw_oa_topic_id,
|
||||
page=page,
|
||||
size=size,
|
||||
title=title,
|
||||
publication_years=publication_years or [],
|
||||
publication_types=publication_types or [],
|
||||
author_ids=author_ids or [],
|
||||
institution_ids=institution_ids or [],
|
||||
language_codes=language_codes or [],
|
||||
sort_by=sort_by,
|
||||
sort_order=sort_order,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/classification/work/{raw_oa_work_id}",
|
||||
operation_id="getWorkClassificationByWorkId",
|
||||
|
||||
@@ -60,6 +60,19 @@ def _institutions_nested_query(institution_ids: list[str]) -> dict:
|
||||
}
|
||||
|
||||
|
||||
def _topics_nested_query(topic_ids: list[str]) -> dict:
|
||||
"""Returns a nested query for filtering works by a list of topic IDs.
|
||||
|
||||
Args:
|
||||
topic_ids (list[str]): A list of topic IDs to filter by.
|
||||
|
||||
Returns:
|
||||
dict: A nested query for filtering works by the specified topic IDs.
|
||||
"""
|
||||
prefixed = [_prefix_id(tid) for tid in topic_ids]
|
||||
return {"nested": {"path": "topics", "query": {"terms": {"topics.id": prefixed}}}}
|
||||
|
||||
|
||||
def _title_query(title: str) -> dict:
|
||||
"""Returns a query for filtering works by title using a multi-match query.
|
||||
|
||||
@@ -87,7 +100,6 @@ def _apply_common_filters(
|
||||
publication_years: list[int] | None,
|
||||
publication_types: list[str] | None,
|
||||
language_codes: list[str] | None,
|
||||
topic_ids: list[str] | None,
|
||||
title: str | None = None,
|
||||
) -> None:
|
||||
"""Applies common filters to the provided list of must conditions for filtering works.
|
||||
@@ -106,10 +118,6 @@ def _apply_common_filters(
|
||||
must.append({"terms": {"type": publication_types}})
|
||||
if language_codes:
|
||||
must.append({"terms": {"language": language_codes}})
|
||||
if topic_ids:
|
||||
must.append(
|
||||
{"nested": {"path": "topics", "query": {"terms": {"topics.id": topic_ids}}}}
|
||||
)
|
||||
if title and len(title.strip()) > 0:
|
||||
must.append(_title_query(title))
|
||||
|
||||
@@ -148,7 +156,7 @@ async def _execute_works_search(
|
||||
Returns:
|
||||
WorkPageV2: The page of works matching the search criteria.
|
||||
"""
|
||||
return await search_works(
|
||||
return await _search_works(
|
||||
source=[
|
||||
"id",
|
||||
"title",
|
||||
@@ -172,8 +180,6 @@ async def _execute_works_search(
|
||||
async def get_works(
|
||||
page: int,
|
||||
size: int,
|
||||
raw_oa_author_id: str | None = None,
|
||||
raw_oa_institution_id: str | None = None,
|
||||
title: str | None = None,
|
||||
author_ids: list[str] | None = None,
|
||||
institution_ids: list[str] | None = None,
|
||||
@@ -189,8 +195,6 @@ async def get_works(
|
||||
Args:
|
||||
page (int): The page number for pagination.
|
||||
size (int): The number of results per page.
|
||||
raw_oa_author_id (Optional[str], optional): The ID of the author to filter by. Defaults to None.
|
||||
raw_oa_institution_id (Optional[str], optional): The ID of the institution to filter by. Defaults to None.
|
||||
title (Optional[str], optional): The title of the works to filter by. Defaults to None.
|
||||
author_ids (Optional[List[str]], optional): A list of author IDs to filter by. Defaults to None.
|
||||
institution_ids (Optional[List[str]], optional): A list of institution IDs to filter by. Defaults to None.
|
||||
@@ -201,34 +205,31 @@ async def get_works(
|
||||
sort_by (WorkSortBy, optional): The field to sort by. Defaults to WorkSortBy.PUBLICATION_YEAR.
|
||||
sort_order (SortDirection, optional): The direction to sort in. Defaults to SortDirection.DESCENDING.
|
||||
|
||||
Raises:
|
||||
ValueError: If neither raw_oa_author_id nor raw_oa_institution_id is provided.
|
||||
|
||||
Returns:
|
||||
WorkPageV2: The page of works matching the criteria.
|
||||
"""
|
||||
if not raw_oa_author_id and not raw_oa_institution_id:
|
||||
raise ValueError(
|
||||
"get_works requires at least one of raw_oa_author_id or raw_oa_institution_id"
|
||||
)
|
||||
|
||||
must: list = []
|
||||
|
||||
if raw_oa_author_id:
|
||||
must.append(_authors_nested_query([raw_oa_author_id]))
|
||||
elif author_ids:
|
||||
must.append(_authors_nested_query(author_ids))
|
||||
if author_ids:
|
||||
must.append(_authors_nested_query(author_ids=author_ids))
|
||||
|
||||
if raw_oa_institution_id:
|
||||
must.append(_institutions_nested_query([raw_oa_institution_id]))
|
||||
elif institution_ids:
|
||||
must.append(_institutions_nested_query(institution_ids))
|
||||
if institution_ids:
|
||||
must.append(_institutions_nested_query(institution_ids=institution_ids))
|
||||
|
||||
if topic_ids:
|
||||
must.append(_topics_nested_query(topic_ids=topic_ids))
|
||||
|
||||
_apply_common_filters(
|
||||
must, publication_years, publication_types, language_codes, topic_ids, title
|
||||
must=must,
|
||||
publication_years=publication_years,
|
||||
publication_types=publication_types,
|
||||
language_codes=language_codes,
|
||||
title=title,
|
||||
)
|
||||
|
||||
return await _execute_works_search(must, page, size, sort_by, sort_order)
|
||||
return await _execute_works_search(
|
||||
must=must, page=page, size=size, sort_by=sort_by, sort_order=sort_order
|
||||
)
|
||||
|
||||
|
||||
async def get_works_by_keywords(
|
||||
@@ -427,7 +428,7 @@ async def get_author_works(
|
||||
return await get_works(
|
||||
page=page,
|
||||
size=size,
|
||||
raw_oa_author_id=raw_oa_author_id,
|
||||
author_ids=[raw_oa_author_id],
|
||||
title=title,
|
||||
institution_ids=institution_ids,
|
||||
publication_years=publication_years,
|
||||
@@ -474,7 +475,7 @@ async def get_institution_works(
|
||||
return await get_works(
|
||||
page=page,
|
||||
size=size,
|
||||
raw_oa_institution_id=raw_oa_institution_id,
|
||||
institution_ids=[raw_oa_institution_id],
|
||||
author_ids=author_ids,
|
||||
title=title,
|
||||
publication_years=publication_years,
|
||||
@@ -486,6 +487,100 @@ async def get_institution_works(
|
||||
)
|
||||
|
||||
|
||||
async def get_topic_works(
|
||||
raw_oa_topic_id: str,
|
||||
page: int,
|
||||
size: int,
|
||||
title: str = "",
|
||||
publication_years: list[int] | None = None,
|
||||
publication_types: list[str] | None = None,
|
||||
institution_ids: list[str] | None = None,
|
||||
author_ids: list[str] | None = None,
|
||||
language_codes: list[str] | None = None,
|
||||
sort_by: WorkSortBy = WorkSortBy.PUBLICATION_YEAR,
|
||||
sort_order: SortDirection = SortDirection.DESCENDING,
|
||||
) -> WorkPageV2:
|
||||
"""Retrieves works for a specific topic based on the provided criteria.
|
||||
|
||||
Args:
|
||||
raw_oa_topic_id (str): The ID of the topic for whom to retrieve works.
|
||||
page (int): The page number of the results to retrieve.
|
||||
size (int): The number of results per page.
|
||||
title (str, optional): The title of the works to filter by. Defaults to "".
|
||||
publication_years (Optional[List[int]], optional): A list of publication years to filter by. Defaults to None.
|
||||
publication_types (Optional[List[str]], optional): A list of publication types to filter by. Defaults to None.
|
||||
institution_ids (Optional[List[str]], optional): A list of institution IDs to filter by. Defaults to None.
|
||||
author_ids (Optional[List[str]], optional): A list of author IDs to filter by. Defaults to None.
|
||||
language_codes (Optional[List[str]], optional): A list of language codes to filter by. Defaults to None.
|
||||
sort_by (WorkSortBy, optional): The field by which to sort the results. Defaults to WorkSortBy.PUBLICATION_YEAR.
|
||||
sort_order (SortDirection, optional): The direction to sort in. Defaults to SortDirection.DESCENDING.
|
||||
|
||||
Returns:
|
||||
WorkPageV2: The page of works matching the criteria.
|
||||
"""
|
||||
|
||||
return await get_works(
|
||||
page=page,
|
||||
size=size,
|
||||
topic_ids=[raw_oa_topic_id],
|
||||
title=title,
|
||||
institution_ids=institution_ids,
|
||||
author_ids=author_ids,
|
||||
publication_years=publication_years,
|
||||
publication_types=publication_types,
|
||||
language_codes=language_codes,
|
||||
sort_by=sort_by,
|
||||
sort_order=sort_order,
|
||||
)
|
||||
|
||||
|
||||
async def search_works(
|
||||
page: int,
|
||||
size: int,
|
||||
title: str | None = None,
|
||||
author_ids: list[str] | None = None,
|
||||
institution_ids: list[str] | None = None,
|
||||
publication_years: list[int] | None = None,
|
||||
publication_types: list[str] | None = None,
|
||||
topic_ids: list[str] | None = None,
|
||||
language_codes: list[str] | None = None,
|
||||
sort_by: WorkSortBy = WorkSortBy.PUBLICATION_YEAR,
|
||||
sort_order: SortDirection = SortDirection.DESCENDING,
|
||||
) -> WorkPageV2:
|
||||
"""Searches for works based on the provided criteria.
|
||||
|
||||
Args:
|
||||
page (int): The page number of the results to retrieve.
|
||||
size (int): The number of results per page.
|
||||
title (str | None, optional): The title of the works to filter by. Defaults to None.
|
||||
author_ids (list[str] | None, optional): A list of author IDs to filter by. Defaults to None.
|
||||
institution_ids (list[str] | None, optional): A list of institution IDs to filter by. Defaults to None.
|
||||
publication_years (list[int] | None, optional): A list of publication years to filter by. Defaults to None.
|
||||
publication_types (list[str] | None, optional): A list of publication types to filter by. Defaults to None.
|
||||
topic_ids (list[str] | None, optional): A list of topic IDs to filter by. Defaults to None.
|
||||
language_codes (list[str] | None, optional): A list of language codes to filter by. Defaults to None.
|
||||
sort_by (WorkSortBy, optional): The field by which to sort the results. Defaults to WorkSortBy.PUBLICATION_YEAR.
|
||||
sort_order (SortDirection, optional): The direction to sort in. Defaults to SortDirection.DESCENDING.
|
||||
|
||||
Returns:
|
||||
WorkPageV2: The page of works matching the criteria.
|
||||
"""
|
||||
|
||||
return await get_works(
|
||||
page=page,
|
||||
size=size,
|
||||
title=title,
|
||||
author_ids=author_ids,
|
||||
institution_ids=institution_ids,
|
||||
publication_years=publication_years,
|
||||
publication_types=publication_types,
|
||||
topic_ids=topic_ids,
|
||||
language_codes=language_codes,
|
||||
sort_by=sort_by,
|
||||
sort_order=sort_order,
|
||||
)
|
||||
|
||||
|
||||
async def get_work(raw_oa_work_id: str, source: list[str] | None = None) -> Work | None:
|
||||
"""Retrieves a work based on its OpenAlex ID.
|
||||
|
||||
@@ -498,7 +593,7 @@ async def get_work(raw_oa_work_id: str, source: list[str] | None = None) -> Work
|
||||
"""
|
||||
|
||||
# search instead of get, because multiple indices are used for works
|
||||
work_page = await search_works(
|
||||
work_page = await _search_works(
|
||||
query={"term": {"id": _prefix_id(raw_oa_work_id)}},
|
||||
source=source,
|
||||
page=0,
|
||||
@@ -510,7 +605,7 @@ async def get_work(raw_oa_work_id: str, source: list[str] | None = None) -> Work
|
||||
return None
|
||||
|
||||
|
||||
async def search_works(
|
||||
async def _search_works(
|
||||
query: dict | None = None,
|
||||
source: list[str] | None = None,
|
||||
page: int = 0,
|
||||
@@ -568,7 +663,7 @@ async def _get_works_by_work_ids_and_institution_id(
|
||||
prefixed_work_ids = [_prefix_id(wid) for wid in work_ids]
|
||||
prefixed_institution_id = _prefix_id(raw_oa_institution_id)
|
||||
|
||||
return await search_works(
|
||||
return await _search_works(
|
||||
query={
|
||||
"bool": {
|
||||
"must": [
|
||||
|
||||
@@ -6,6 +6,8 @@ api.module.ts
|
||||
api/api.ts
|
||||
api/auth.service.ts
|
||||
api/authorsV2.service.ts
|
||||
api/bUNDInstitutions.service.ts
|
||||
api/backgroundJobs.service.ts
|
||||
api/bookmarks.service.ts
|
||||
api/companyConnections.service.ts
|
||||
api/dFGInstitutions.service.ts
|
||||
@@ -19,7 +21,6 @@ api/keywords.service.ts
|
||||
api/news.service.ts
|
||||
api/organization.service.ts
|
||||
api/patents.service.ts
|
||||
api/personNetwork.service.ts
|
||||
api/persons.service.ts
|
||||
api/projects.service.ts
|
||||
api/ranking.service.ts
|
||||
@@ -42,7 +43,10 @@ model/authorAffiliationsInner.ts
|
||||
model/authorCountsByYearInner.ts
|
||||
model/authorIds.ts
|
||||
model/authorMetricsRequest.ts
|
||||
model/authorNetworkNode.ts
|
||||
model/authorNode.ts
|
||||
model/authorOrientationProfile.ts
|
||||
model/authorOrientationProfileStatus.ts
|
||||
model/authorOrientationProfilesRequest.ts
|
||||
model/authorPage.ts
|
||||
model/authorParsedLongestName.ts
|
||||
model/authorPositionCount.ts
|
||||
@@ -50,28 +54,32 @@ model/authorStaticStats.ts
|
||||
model/authorSummaryStats.ts
|
||||
model/authorTopicProfile.ts
|
||||
model/authorTopicStats.ts
|
||||
model/authorsFilterProperties.ts
|
||||
model/authorsListResponse.ts
|
||||
model/authorship.ts
|
||||
model/autocompleteLocationItem.ts
|
||||
model/autocompleteResponse.ts
|
||||
model/autocompleteResponseMeta.ts
|
||||
model/autocompleteResponseResultsInner.ts
|
||||
model/availableImages.ts
|
||||
model/award.ts
|
||||
model/backgroundJobTask.ts
|
||||
model/bmbfProjectStatusStatistics.ts
|
||||
model/bodyChangePassword.ts
|
||||
model/bodyGetAccessToken.ts
|
||||
model/bodyLogin.ts
|
||||
model/bodyRequestOtk.ts
|
||||
model/bodyRequestPasswordReset.ts
|
||||
model/bodyResetPassword.ts
|
||||
model/bundInstitutionSummary.ts
|
||||
model/bundInstitutionSummaryPage.ts
|
||||
model/bundProjectDetails.ts
|
||||
model/bundProjectPage.ts
|
||||
model/bundProjectSummary.ts
|
||||
model/careerMetrics.ts
|
||||
model/careerStage.ts
|
||||
model/collaborationNetwork.ts
|
||||
model/collaborationNetworkEdge.ts
|
||||
model/collaborationNetworkNodeType.ts
|
||||
model/collaborationGraph.ts
|
||||
model/collaborationGraphStatus.ts
|
||||
model/collaborationGraphStatusResponse.ts
|
||||
model/companyConnection.ts
|
||||
model/companyConnectionsAvailability.ts
|
||||
model/companyConnectionsResponse.ts
|
||||
@@ -94,8 +102,17 @@ model/dfgInstitutionSummaryPage.ts
|
||||
model/dfgPersonSummary.ts
|
||||
model/dfgPersonSummaryPage.ts
|
||||
model/dfgProjectDetails.ts
|
||||
model/dfgProjectInstitutionRole.ts
|
||||
model/dfgProjectPage.ts
|
||||
model/dfgProjectPersonRole.ts
|
||||
model/dfgProjectPublicationSummary.ts
|
||||
model/dfgProjectSubjectArea.ts
|
||||
model/dfgProjectSubprojectSummary.ts
|
||||
model/dfgProjectSummary.ts
|
||||
model/dfgProjectTopic.ts
|
||||
model/dfgProjectTopics.ts
|
||||
model/dockerHealth.ts
|
||||
model/edge.ts
|
||||
model/euCordisEurosciVocSummary.ts
|
||||
model/euCordisOrganizationSelectorPage.ts
|
||||
model/euCordisOrganizationSelectorSummary.ts
|
||||
@@ -106,12 +123,11 @@ model/euCordisProjectSummary.ts
|
||||
model/euCordisProjectType.ts
|
||||
model/euCordisTopicSummary.ts
|
||||
model/euProjectData.ts
|
||||
model/euProjectStatusStatistics.ts
|
||||
model/extractedKeywords.ts
|
||||
model/extractedKeywordsLLM.ts
|
||||
model/extractedKeywordsResponse.ts
|
||||
model/fileUpload.ts
|
||||
model/filterInformation.ts
|
||||
model/filterProperties.ts
|
||||
model/filterType.ts
|
||||
model/fp7EurosciVoc.ts
|
||||
model/fp7LegalBasis.ts
|
||||
@@ -155,12 +171,17 @@ model/institution.ts
|
||||
model/institutionFunderSummary.ts
|
||||
model/institutionGeo.ts
|
||||
model/institutionIds.ts
|
||||
model/institutionInformation.ts
|
||||
model/institutionNetworkNode.ts
|
||||
model/institutionNode.ts
|
||||
model/institutionPage.ts
|
||||
model/institutionPageV2.ts
|
||||
model/institutionsListResponse.ts
|
||||
model/ipcClassification.ts
|
||||
model/jobDefinitionCreateRequest.ts
|
||||
model/jobDefinitionUpdateRequest.ts
|
||||
model/jobRun.ts
|
||||
model/jobRunLogs.ts
|
||||
model/jobRunStatus.ts
|
||||
model/jobTriggeredBy.ts
|
||||
model/keywordEntry.ts
|
||||
model/keywordEntryWithTopic.ts
|
||||
model/keywordEvidence.ts
|
||||
@@ -215,9 +236,11 @@ model/rankedAuthor.ts
|
||||
model/rankingResponse.ts
|
||||
model/rankingWeights.ts
|
||||
model/rebuildResponse.ts
|
||||
model/registryHealth.ts
|
||||
model/score.ts
|
||||
model/selectedAuthorsRequest.ts
|
||||
model/sortDirection.ts
|
||||
model/startCollaborationGraphResponse.ts
|
||||
model/subfieldShare.ts
|
||||
model/timespan.ts
|
||||
model/tokenType.ts
|
||||
@@ -232,10 +255,15 @@ model/topicDomain.ts
|
||||
model/topicField.ts
|
||||
model/topicHeatmap.ts
|
||||
model/topicHeatmapField.ts
|
||||
model/topicHeatmapSubfield.ts
|
||||
model/topicHeatmapTopic.ts
|
||||
model/topicHeatmapValue.ts
|
||||
model/topicIds.ts
|
||||
model/topicPageV2.ts
|
||||
model/topicSortBy.ts
|
||||
model/topicSubfield.ts
|
||||
model/topicWordCloud.ts
|
||||
model/topicWordCloudWord.ts
|
||||
model/topicYearlyData.ts
|
||||
model/topicsByTime.ts
|
||||
model/topicsByYear.ts
|
||||
@@ -269,7 +297,7 @@ model/workHasContent.ts
|
||||
model/workIds.ts
|
||||
model/workKeyword.ts
|
||||
model/workMeshInner.ts
|
||||
model/workNetworkNode.ts
|
||||
model/workNode.ts
|
||||
model/workPage.ts
|
||||
model/workPageV2.ts
|
||||
model/workPrimaryCategory.ts
|
||||
@@ -278,9 +306,7 @@ model/workSustainableDevelopmentGoalsInner.ts
|
||||
model/workTopic.ts
|
||||
model/workTopicDomain.ts
|
||||
model/workTopicField.ts
|
||||
model/workTopicInformation.ts
|
||||
model/workTopicSubfield.ts
|
||||
model/worksFilterProperties.ts
|
||||
model/worksListResponse.ts
|
||||
model/yearlyData.ts
|
||||
param.ts
|
||||
|
||||
@@ -46,10 +46,10 @@ npm link
|
||||
In your project:
|
||||
|
||||
```console
|
||||
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.
|
||||
Published packages are not effected by this issue.
|
||||
|
||||
@@ -58,22 +58,22 @@ Published packages are not effected by this issue.
|
||||
In your Angular project:
|
||||
|
||||
```typescript
|
||||
|
||||
import { ApplicationConfig } from '@angular/core';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { provideApi } from '';
|
||||
|
||||
export const appConfig: ApplicationConfig = {
|
||||
providers: [
|
||||
// ...
|
||||
provideHttpClient(),
|
||||
provideApi(),
|
||||
],
|
||||
providers: [
|
||||
// ...
|
||||
provideHttpClient(),
|
||||
provideApi()
|
||||
],
|
||||
};
|
||||
```
|
||||
|
||||
**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:
|
||||
|
||||
```typescript
|
||||
import { ApiModule } from '';
|
||||
```
|
||||
@@ -86,11 +86,11 @@ import { provideHttpClient } from '@angular/common/http';
|
||||
import { provideApi } from '';
|
||||
|
||||
export const appConfig: ApplicationConfig = {
|
||||
providers: [
|
||||
// ...
|
||||
provideHttpClient(),
|
||||
provideApi('http://localhost:9999'),
|
||||
],
|
||||
providers: [
|
||||
// ...
|
||||
provideHttpClient(),
|
||||
provideApi('http://localhost:9999')
|
||||
],
|
||||
};
|
||||
```
|
||||
|
||||
@@ -101,15 +101,15 @@ import { provideHttpClient } from '@angular/common/http';
|
||||
import { provideApi } from '';
|
||||
|
||||
export const appConfig: ApplicationConfig = {
|
||||
providers: [
|
||||
// ...
|
||||
provideHttpClient(),
|
||||
provideApi({
|
||||
withCredentials: true,
|
||||
username: 'user',
|
||||
password: 'password',
|
||||
}),
|
||||
],
|
||||
providers: [
|
||||
// ...
|
||||
provideHttpClient(),
|
||||
provideApi({
|
||||
withCredentials: true,
|
||||
username: 'user',
|
||||
password: 'password'
|
||||
})
|
||||
],
|
||||
};
|
||||
```
|
||||
|
||||
@@ -120,22 +120,21 @@ import { provideHttpClient } from '@angular/common/http';
|
||||
import { provideApi, Configuration } from '';
|
||||
|
||||
export const appConfig: ApplicationConfig = {
|
||||
providers: [
|
||||
// ...
|
||||
provideHttpClient(),
|
||||
{
|
||||
provide: Configuration,
|
||||
useFactory: (authService: AuthService) =>
|
||||
new Configuration({
|
||||
basePath: 'http://localhost:9999',
|
||||
withCredentials: true,
|
||||
username: authService.getUsername(),
|
||||
password: authService.getPassword(),
|
||||
}),
|
||||
deps: [AuthService],
|
||||
multi: false,
|
||||
},
|
||||
],
|
||||
providers: [
|
||||
// ...
|
||||
provideHttpClient(),
|
||||
{
|
||||
provide: Configuration,
|
||||
useFactory: (authService: AuthService) => new Configuration({
|
||||
basePath: 'http://localhost:9999',
|
||||
withCredentials: true,
|
||||
username: authService.getUsername(),
|
||||
password: authService.getPassword(),
|
||||
}),
|
||||
deps: [AuthService],
|
||||
multi: false
|
||||
}
|
||||
],
|
||||
};
|
||||
```
|
||||
|
||||
@@ -152,12 +151,12 @@ import { HttpClientModule } from '@angular/common/http';
|
||||
import { environment } from '../environments/environment';
|
||||
|
||||
export const appConfig: ApplicationConfig = {
|
||||
providers: [
|
||||
// ...
|
||||
provideHttpClient(),
|
||||
provideUserApi(environment.basePath),
|
||||
provideAdminApi(environment.basePath),
|
||||
],
|
||||
providers: [
|
||||
// ...
|
||||
provideHttpClient(),
|
||||
provideUserApi(environment.basePath),
|
||||
provideAdminApi(environment.basePath),
|
||||
],
|
||||
};
|
||||
```
|
||||
|
||||
@@ -177,8 +176,8 @@ Example value for use in your Configuration-Provider:
|
||||
|
||||
```typescript
|
||||
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
|
||||
|
||||
@@ -1,109 +1,83 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* 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 { Configuration } from './configuration';
|
||||
|
||||
export class BaseService {
|
||||
protected basePath = 'http://localhost:8000';
|
||||
public defaultHeaders = new HttpHeaders();
|
||||
public configuration: Configuration;
|
||||
public encoder: HttpParameterCodec;
|
||||
protected basePath = 'http://localhost:8000';
|
||||
public defaultHeaders = new HttpHeaders();
|
||||
public configuration: Configuration;
|
||||
public encoder: HttpParameterCodec;
|
||||
|
||||
constructor(basePath?: string | string[], configuration?: Configuration) {
|
||||
this.configuration = configuration || new Configuration();
|
||||
if (typeof this.configuration.basePath !== 'string') {
|
||||
const firstBasePath = Array.isArray(basePath) ? basePath[0] : undefined;
|
||||
if (firstBasePath != undefined) {
|
||||
basePath = firstBasePath;
|
||||
}
|
||||
constructor(basePath?: string|string[], configuration?: Configuration) {
|
||||
this.configuration = configuration || new Configuration();
|
||||
if (typeof this.configuration.basePath !== 'string') {
|
||||
const firstBasePath = Array.isArray(basePath) ? basePath[0] : undefined;
|
||||
if (firstBasePath != undefined) {
|
||||
basePath = firstBasePath;
|
||||
}
|
||||
|
||||
if (typeof basePath !== 'string') {
|
||||
basePath = this.basePath;
|
||||
}
|
||||
this.configuration.basePath = basePath;
|
||||
}
|
||||
this.encoder = this.configuration.encoder || new CustomHttpParameterCodec();
|
||||
}
|
||||
|
||||
protected canConsumeForm(consumes: string[]): boolean {
|
||||
return consumes.indexOf('multipart/form-data') !== -1;
|
||||
}
|
||||
|
||||
protected addToHttpParams(
|
||||
httpParams: HttpParams,
|
||||
value: any,
|
||||
key?: string,
|
||||
isDeep: boolean = false,
|
||||
): 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 {
|
||||
if (value === null || value === undefined) {
|
||||
return httpParams;
|
||||
}
|
||||
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');
|
||||
if (typeof basePath !== 'string') {
|
||||
basePath = this.basePath;
|
||||
}
|
||||
this.configuration.basePath = basePath;
|
||||
}
|
||||
} 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);
|
||||
this.encoder = this.configuration.encoder || new CustomHttpParameterCodec();
|
||||
}
|
||||
|
||||
protected canConsumeForm(consumes: string[]): boolean {
|
||||
return consumes.indexOf('multipart/form-data') !== -1;
|
||||
}
|
||||
|
||||
protected addToHttpParams(httpParams: HttpParams, value: any, key?: string, isDeep: boolean = false): 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 {
|
||||
if (value === null || value === undefined) {
|
||||
return httpParams;
|
||||
}
|
||||
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");
|
||||
}
|
||||
throw Error('key may not be null if value is not object or array');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,42 +1,30 @@
|
||||
import {
|
||||
NgModule,
|
||||
ModuleWithProviders,
|
||||
SkipSelf,
|
||||
Optional,
|
||||
} from '@angular/core';
|
||||
import { NgModule, ModuleWithProviders, SkipSelf, Optional } from '@angular/core';
|
||||
import { Configuration } from './configuration';
|
||||
import { HttpClient } from '@angular/common/http';
|
||||
|
||||
|
||||
@NgModule({
|
||||
imports: [],
|
||||
imports: [],
|
||||
declarations: [],
|
||||
exports: [],
|
||||
providers: [],
|
||||
exports: [],
|
||||
providers: []
|
||||
})
|
||||
export class ApiModule {
|
||||
public static forRoot(
|
||||
configurationFactory: () => Configuration,
|
||||
): ModuleWithProviders<ApiModule> {
|
||||
return {
|
||||
ngModule: ApiModule,
|
||||
providers: [{ provide: Configuration, useFactory: configurationFactory }],
|
||||
};
|
||||
}
|
||||
public static forRoot(configurationFactory: () => Configuration): ModuleWithProviders<ApiModule> {
|
||||
return {
|
||||
ngModule: ApiModule,
|
||||
providers: [ { provide: Configuration, useFactory: configurationFactory } ]
|
||||
};
|
||||
}
|
||||
|
||||
constructor(
|
||||
@Optional() @SkipSelf() parentModule: ApiModule,
|
||||
@Optional() http: HttpClient,
|
||||
) {
|
||||
if (parentModule) {
|
||||
throw new Error(
|
||||
'ApiModule is already loaded. Import in your base AppModule only.',
|
||||
);
|
||||
constructor( @Optional() @SkipSelf() parentModule: ApiModule,
|
||||
@Optional() http: HttpClient) {
|
||||
if (parentModule) {
|
||||
throw new Error('ApiModule is already loaded. Import in your base AppModule only.');
|
||||
}
|
||||
if (!http) {
|
||||
throw new Error('You need to import the HttpClientModule in your AppModule! \n' +
|
||||
'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',
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,8 @@ export * from './auth.service';
|
||||
import { AuthService } from './auth.service';
|
||||
export * from './authorsV2.service';
|
||||
import { AuthorsV2Service } from './authorsV2.service';
|
||||
export * from './bUNDInstitutions.service';
|
||||
import { BUNDInstitutionsService } from './bUNDInstitutions.service';
|
||||
export * from './backgroundJobs.service';
|
||||
import { BackgroundJobsService } from './backgroundJobs.service';
|
||||
export * from './bookmarks.service';
|
||||
@@ -30,8 +32,6 @@ export * from './organization.service';
|
||||
import { OrganizationService } from './organization.service';
|
||||
export * from './patents.service';
|
||||
import { PatentsService } from './patents.service';
|
||||
export * from './personNetwork.service';
|
||||
import { PersonNetworkService } from './personNetwork.service';
|
||||
export * from './persons.service';
|
||||
import { PersonsService } from './persons.service';
|
||||
export * from './projects.service';
|
||||
@@ -51,6 +51,7 @@ import { WorksV2Service } from './worksV2.service';
|
||||
export const APIS = [
|
||||
AuthService,
|
||||
AuthorsV2Service,
|
||||
BUNDInstitutionsService,
|
||||
BackgroundJobsService,
|
||||
BookmarksService,
|
||||
CompanyConnectionsService,
|
||||
@@ -65,7 +66,6 @@ export const APIS = [
|
||||
NewsService,
|
||||
OrganizationService,
|
||||
PatentsService,
|
||||
PersonNetworkService,
|
||||
PersonsService,
|
||||
ProjectsService,
|
||||
RankingService,
|
||||
|
||||
+908
-1699
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
@@ -9,250 +9,352 @@
|
||||
*/
|
||||
/* tslint:disable:no-unused-variable member-ordering */
|
||||
|
||||
import { Inject, Injectable, Optional } from '@angular/core';
|
||||
import {
|
||||
HttpClient,
|
||||
HttpHeaders,
|
||||
HttpParams,
|
||||
HttpResponse,
|
||||
HttpEvent,
|
||||
HttpParameterCodec,
|
||||
HttpContext,
|
||||
} from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
import { Inject, Injectable, Optional } from '@angular/core';
|
||||
import { HttpClient, HttpHeaders, HttpParams,
|
||||
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
|
||||
} from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
// @ts-ignore
|
||||
import { Author } from '../model/author';
|
||||
// @ts-ignore
|
||||
import { AuthorPage } from '../model/authorPage';
|
||||
// @ts-ignore
|
||||
import { CollaborationGraphStatusResponse } from '../model/collaborationGraphStatusResponse';
|
||||
// @ts-ignore
|
||||
import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||
// @ts-ignore
|
||||
import { StartCollaborationGraphResponse } from '../model/startCollaborationGraphResponse';
|
||||
|
||||
// @ts-ignore
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BaseService } from '../api.base.service';
|
||||
|
||||
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class AuthorsV2Service extends BaseService {
|
||||
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,
|
||||
);
|
||||
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
|
||||
super(basePath, configuration);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext =
|
||||
options?.context ?? new HttpContext();
|
||||
/**
|
||||
* 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> {
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>query, 'query');
|
||||
|
||||
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 localVarHeaders = this.defaultHeaders;
|
||||
|
||||
let localVarPath = `/api/authors/v2/autocomplete/selector`;
|
||||
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 localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 });
|
||||
if (authorIds) {
|
||||
authorIds.forEach((element) => {
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>element,
|
||||
'author_ids',
|
||||
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/autocomplete/selector`;
|
||||
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
|
||||
}
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
/**
|
||||
* Returns an author for a given author ID.
|
||||
* @endpoint get /api/authors/v2/{raw_oa_author_id}
|
||||
* @param rawOaAuthorId The ID of the author 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 getAuthorById(rawOaAuthorId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Author>;
|
||||
public getAuthorById(rawOaAuthorId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Author>>;
|
||||
public getAuthorById(rawOaAuthorId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Author>>;
|
||||
public getAuthorById(rawOaAuthorId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (rawOaAuthorId === null || rawOaAuthorId === undefined) {
|
||||
throw new Error('Required parameter rawOaAuthorId was null or undefined when calling getAuthorById.');
|
||||
}
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
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/${this.configuration.encodeParam({name: "rawOaAuthorId", value: rawOaAuthorId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<Author>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
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.
|
||||
* @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> {
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||
if (authorIds) {
|
||||
authorIds.forEach((element) => {
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>element, 'author_ids');
|
||||
})
|
||||
}
|
||||
|
||||
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 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
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the status of a collaboration graph generation task.
|
||||
* @endpoint get /api/authors/v2/collaboration-graph/{graph_id}/status
|
||||
* @param graphId The ID of the collaboration graph generation task.
|
||||
* @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 getCollaborationGraphStatus(graphId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<CollaborationGraphStatusResponse>;
|
||||
public getCollaborationGraphStatus(graphId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<CollaborationGraphStatusResponse>>;
|
||||
public getCollaborationGraphStatus(graphId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<CollaborationGraphStatusResponse>>;
|
||||
public getCollaborationGraphStatus(graphId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (graphId === null || graphId === undefined) {
|
||||
throw new Error('Required parameter graphId was null or undefined when calling getCollaborationGraphStatus.');
|
||||
}
|
||||
|
||||
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/collaboration-graph/${this.configuration.encodeParam({name: "graphId", value: graphId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}/status`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<CollaborationGraphStatusResponse>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a collaboration graph for a given author ID.
|
||||
* @endpoint post /api/authors/v2/collaboration-graph
|
||||
* @param rawOaAuthorId The raw OpenAlex author ID for which to retrieve the collaboration graph.
|
||||
* @param yearFrom The starting year to filter the works by (optional).
|
||||
* @param yearTo The ending year to filter the works by (optional).
|
||||
* @param minCollaborators The minimum number of collaborators to filter the works by (optional).
|
||||
* @param maxCollaborators The maximum number of collaborators to filter the works by (optional).
|
||||
* @param topicIds A list of topic IDs to filter the works by (optional).
|
||||
* @param institutionIds A list of institution IDs to filter the works by (optional).
|
||||
* @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 startCollaborationGraph(rawOaAuthorId: string, yearFrom?: number, yearTo?: number, minCollaborators?: number, maxCollaborators?: number, topicIds?: Array<string>, institutionIds?: Array<string>, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<StartCollaborationGraphResponse>;
|
||||
public startCollaborationGraph(rawOaAuthorId: string, yearFrom?: number, yearTo?: number, minCollaborators?: number, maxCollaborators?: number, topicIds?: Array<string>, institutionIds?: Array<string>, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<StartCollaborationGraphResponse>>;
|
||||
public startCollaborationGraph(rawOaAuthorId: string, yearFrom?: number, yearTo?: number, minCollaborators?: number, maxCollaborators?: number, topicIds?: Array<string>, institutionIds?: Array<string>, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<StartCollaborationGraphResponse>>;
|
||||
public startCollaborationGraph(rawOaAuthorId: string, yearFrom?: number, yearTo?: number, minCollaborators?: number, maxCollaborators?: number, topicIds?: Array<string>, institutionIds?: Array<string>, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (rawOaAuthorId === null || rawOaAuthorId === undefined) {
|
||||
throw new Error('Required parameter rawOaAuthorId was null or undefined when calling startCollaborationGraph.');
|
||||
}
|
||||
|
||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>rawOaAuthorId, 'raw_oa_author_id');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>yearFrom, 'year_from');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>yearTo, 'year_to');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>minCollaborators, 'min_collaborators');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>maxCollaborators, 'max_collaborators');
|
||||
if (topicIds) {
|
||||
topicIds.forEach((element) => {
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>element, 'topic_ids');
|
||||
})
|
||||
}
|
||||
if (institutionIds) {
|
||||
institutionIds.forEach((element) => {
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>element, 'institution_ids');
|
||||
})
|
||||
}
|
||||
|
||||
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/collaboration-graph`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<StartCollaborationGraphResponse>('post', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined ? { transferCache: localVarTransferCache } : {}),
|
||||
reportProgress: reportProgress
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
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,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,258 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
/* tslint:disable:no-unused-variable member-ordering */
|
||||
|
||||
import { Inject, Injectable, Optional } from '@angular/core';
|
||||
import {
|
||||
HttpClient,
|
||||
HttpHeaders,
|
||||
HttpParams,
|
||||
HttpResponse,
|
||||
HttpEvent,
|
||||
HttpParameterCodec,
|
||||
HttpContext,
|
||||
} from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
// @ts-ignore
|
||||
import { BundInstitutionSummaryPage } from '../model/bundInstitutionSummaryPage';
|
||||
// @ts-ignore
|
||||
import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||
|
||||
// @ts-ignore
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BaseService } from '../api.base.service';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class BUNDInstitutionsService extends BaseService {
|
||||
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/bund/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 getBundInstitutionAutocompleteForSelector(
|
||||
query?: string,
|
||||
observe?: 'body',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<BundInstitutionSummaryPage>;
|
||||
public getBundInstitutionAutocompleteForSelector(
|
||||
query?: string,
|
||||
observe?: 'response',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpResponse<BundInstitutionSummaryPage>>;
|
||||
public getBundInstitutionAutocompleteForSelector(
|
||||
query?: string,
|
||||
observe?: 'events',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpEvent<BundInstitutionSummaryPage>>;
|
||||
public getBundInstitutionAutocompleteForSelector(
|
||||
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 =
|
||||
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/bund/institutions/autocomplete/selector`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<BundInstitutionSummaryPage>(
|
||||
'get',
|
||||
`${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
params: localVarQueryParameters,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined
|
||||
? { transferCache: localVarTransferCache }
|
||||
: {}),
|
||||
reportProgress: reportProgress,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a list of institutions based on their names.
|
||||
* @endpoint get /api/bund/institutions/names
|
||||
* @param institutionNames A list of institution names 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 getBundInstitutionsByName(
|
||||
institutionNames?: Array<string>,
|
||||
observe?: 'body',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<BundInstitutionSummaryPage>;
|
||||
public getBundInstitutionsByName(
|
||||
institutionNames?: Array<string>,
|
||||
observe?: 'response',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpResponse<BundInstitutionSummaryPage>>;
|
||||
public getBundInstitutionsByName(
|
||||
institutionNames?: Array<string>,
|
||||
observe?: 'events',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpEvent<BundInstitutionSummaryPage>>;
|
||||
public getBundInstitutionsByName(
|
||||
institutionNames?: 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 (institutionNames) {
|
||||
institutionNames.forEach((element) => {
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>element,
|
||||
'institution_names',
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
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/bund/institutions/names`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<BundInstitutionSummaryPage>(
|
||||
'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
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
@@ -9,18 +9,12 @@
|
||||
*/
|
||||
/* tslint:disable:no-unused-variable member-ordering */
|
||||
|
||||
import { Inject, Injectable, Optional } from '@angular/core';
|
||||
import {
|
||||
HttpClient,
|
||||
HttpHeaders,
|
||||
HttpParams,
|
||||
HttpResponse,
|
||||
HttpEvent,
|
||||
HttpParameterCodec,
|
||||
HttpContext,
|
||||
} from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
import { Inject, Injectable, Optional } from '@angular/core';
|
||||
import { HttpClient, HttpHeaders, HttpParams,
|
||||
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
|
||||
} from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
// @ts-ignore
|
||||
import { CreatePersonBookmark } from '../model/createPersonBookmark';
|
||||
@@ -30,375 +24,206 @@ import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||
import { PersonBookmarkResponse } from '../model/personBookmarkResponse';
|
||||
|
||||
// @ts-ignore
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BaseService } from '../api.base.service';
|
||||
|
||||
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class BookmarksService extends BaseService {
|
||||
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.',
|
||||
);
|
||||
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
|
||||
super(basePath, configuration);
|
||||
}
|
||||
|
||||
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.');
|
||||
}
|
||||
|
||||
// authentication (HTTPBearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders(
|
||||
'HTTPBearer',
|
||||
'Authorization',
|
||||
localVarHeaders,
|
||||
'Bearer ',
|
||||
);
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Accept',
|
||||
localVarHttpHeaderAcceptSelected,
|
||||
);
|
||||
// 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/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 =
|
||||
options?.context ?? new HttpContext();
|
||||
/**
|
||||
* 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> {
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// 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,
|
||||
);
|
||||
// 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
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
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';
|
||||
}
|
||||
/**
|
||||
* 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
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
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,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
@@ -9,18 +9,12 @@
|
||||
*/
|
||||
/* tslint:disable:no-unused-variable member-ordering */
|
||||
|
||||
import { Inject, Injectable, Optional } from '@angular/core';
|
||||
import {
|
||||
HttpClient,
|
||||
HttpHeaders,
|
||||
HttpParams,
|
||||
HttpResponse,
|
||||
HttpEvent,
|
||||
HttpParameterCodec,
|
||||
HttpContext,
|
||||
} from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
import { Inject, Injectable, Optional } from '@angular/core';
|
||||
import { HttpClient, HttpHeaders, HttpParams,
|
||||
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
|
||||
} from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
// @ts-ignore
|
||||
import { CompanyConnectionsAvailability } from '../model/companyConnectionsAvailability';
|
||||
@@ -30,249 +24,137 @@ import { CompanyConnectionsResponse } from '../model/companyConnectionsResponse'
|
||||
import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||
|
||||
// @ts-ignore
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BaseService } from '../api.base.service';
|
||||
|
||||
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class CompanyConnectionsService extends BaseService {
|
||||
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.',
|
||||
);
|
||||
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
|
||||
super(basePath, configuration);
|
||||
}
|
||||
|
||||
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.');
|
||||
}
|
||||
|
||||
// authentication (HTTPBearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders(
|
||||
'HTTPBearer',
|
||||
'Authorization',
|
||||
localVarHeaders,
|
||||
'Bearer ',
|
||||
);
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Accept',
|
||||
localVarHttpHeaderAcceptSelected,
|
||||
);
|
||||
// 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/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 =
|
||||
options?.context ?? new HttpContext();
|
||||
/**
|
||||
* 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.');
|
||||
}
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
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';
|
||||
}
|
||||
// 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
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
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,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
@@ -9,18 +9,12 @@
|
||||
*/
|
||||
/* tslint:disable:no-unused-variable member-ordering */
|
||||
|
||||
import { Inject, Injectable, Optional } from '@angular/core';
|
||||
import {
|
||||
HttpClient,
|
||||
HttpHeaders,
|
||||
HttpParams,
|
||||
HttpResponse,
|
||||
HttpEvent,
|
||||
HttpParameterCodec,
|
||||
HttpContext,
|
||||
} from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
import { Inject, Injectable, Optional } from '@angular/core';
|
||||
import { HttpClient, HttpHeaders, HttpParams,
|
||||
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
|
||||
} from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
// @ts-ignore
|
||||
import { DfgInstitutionSummaryPage } from '../model/dfgInstitutionSummaryPage';
|
||||
@@ -28,231 +22,137 @@ import { DfgInstitutionSummaryPage } from '../model/dfgInstitutionSummaryPage';
|
||||
import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||
|
||||
// @ts-ignore
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BaseService } from '../api.base.service';
|
||||
|
||||
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class DFGInstitutionsService extends BaseService {
|
||||
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,
|
||||
);
|
||||
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
|
||||
super(basePath, configuration);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext =
|
||||
options?.context ?? new HttpContext();
|
||||
/**
|
||||
* 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> {
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>query, 'query');
|
||||
|
||||
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 localVarHeaders = this.defaultHeaders;
|
||||
|
||||
let localVarPath = `/api/dfg/institutions/autocomplete/selector`;
|
||||
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 localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 });
|
||||
if (institutionIds) {
|
||||
institutionIds.forEach((element) => {
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>element,
|
||||
'institution_ids',
|
||||
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/autocomplete/selector`;
|
||||
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
|
||||
}
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
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> {
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Accept',
|
||||
localVarHttpHeaderAcceptSelected,
|
||||
);
|
||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||
if (institutionIds) {
|
||||
institutionIds.forEach((element) => {
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>element, 'institution_ids');
|
||||
})
|
||||
}
|
||||
|
||||
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,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
@@ -9,18 +9,12 @@
|
||||
*/
|
||||
/* tslint:disable:no-unused-variable member-ordering */
|
||||
|
||||
import { Inject, Injectable, Optional } from '@angular/core';
|
||||
import {
|
||||
HttpClient,
|
||||
HttpHeaders,
|
||||
HttpParams,
|
||||
HttpResponse,
|
||||
HttpEvent,
|
||||
HttpParameterCodec,
|
||||
HttpContext,
|
||||
} from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
import { Inject, Injectable, Optional } from '@angular/core';
|
||||
import { HttpClient, HttpHeaders, HttpParams,
|
||||
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
|
||||
} from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
// @ts-ignore
|
||||
import { DfgPersonSummaryPage } from '../model/dfgPersonSummaryPage';
|
||||
@@ -28,231 +22,137 @@ import { DfgPersonSummaryPage } from '../model/dfgPersonSummaryPage';
|
||||
import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||
|
||||
// @ts-ignore
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BaseService } from '../api.base.service';
|
||||
|
||||
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class DFGPersonsService extends BaseService {
|
||||
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,
|
||||
);
|
||||
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
|
||||
super(basePath, configuration);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext =
|
||||
options?.context ?? new HttpContext();
|
||||
/**
|
||||
* 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> {
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>query, 'query');
|
||||
|
||||
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 localVarHeaders = this.defaultHeaders;
|
||||
|
||||
let localVarPath = `/api/dfg/persons/autocomplete/selector`;
|
||||
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 localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 });
|
||||
if (personIds) {
|
||||
personIds.forEach((element) => {
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>element,
|
||||
'person_ids',
|
||||
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/autocomplete/selector`;
|
||||
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
|
||||
}
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
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> {
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Accept',
|
||||
localVarHttpHeaderAcceptSelected,
|
||||
);
|
||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||
if (personIds) {
|
||||
personIds.forEach((element) => {
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>element, 'person_ids');
|
||||
})
|
||||
}
|
||||
|
||||
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
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
@@ -9,18 +9,12 @@
|
||||
*/
|
||||
/* tslint:disable:no-unused-variable member-ordering */
|
||||
|
||||
import { Inject, Injectable, Optional } from '@angular/core';
|
||||
import {
|
||||
HttpClient,
|
||||
HttpHeaders,
|
||||
HttpParams,
|
||||
HttpResponse,
|
||||
HttpEvent,
|
||||
HttpParameterCodec,
|
||||
HttpContext,
|
||||
} from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
import { Inject, Injectable, Optional } from '@angular/core';
|
||||
import { HttpClient, HttpHeaders, HttpParams,
|
||||
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
|
||||
} from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
// @ts-ignore
|
||||
import { FundersByAuthorResponse } from '../model/fundersByAuthorResponse';
|
||||
@@ -30,246 +24,138 @@ import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||
import { PublicationsByAuthorResponse } from '../model/publicationsByAuthorResponse';
|
||||
|
||||
// @ts-ignore
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BaseService } from '../api.base.service';
|
||||
|
||||
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class FundingService extends BaseService {
|
||||
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.',
|
||||
);
|
||||
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
|
||||
super(basePath, configuration);
|
||||
}
|
||||
|
||||
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.');
|
||||
}
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
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/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 =
|
||||
options?.context ?? new HttpContext();
|
||||
/**
|
||||
* 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.');
|
||||
}
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>page, 'page');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>pageSize, 'page_size');
|
||||
|
||||
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 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
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
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,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
@@ -9,355 +9,205 @@
|
||||
*/
|
||||
/* tslint:disable:no-unused-variable member-ordering */
|
||||
|
||||
import { Inject, Injectable, Optional } from '@angular/core';
|
||||
import {
|
||||
HttpClient,
|
||||
HttpHeaders,
|
||||
HttpParams,
|
||||
HttpResponse,
|
||||
HttpEvent,
|
||||
HttpParameterCodec,
|
||||
HttpContext,
|
||||
} from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
import { Inject, Injectable, Optional } from '@angular/core';
|
||||
import { HttpClient, HttpHeaders, HttpParams,
|
||||
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
|
||||
} from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
// @ts-ignore
|
||||
import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||
|
||||
// @ts-ignore
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BaseService } from '../api.base.service';
|
||||
|
||||
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class INSEServiceService extends BaseService {
|
||||
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,
|
||||
);
|
||||
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
|
||||
super(basePath, configuration);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext =
|
||||
options?.context ?? new HttpContext();
|
||||
/**
|
||||
* 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> {
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>pageSize, 'page_size');
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>saveJson, 'save_json');
|
||||
|
||||
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 localVarHeaders = this.defaultHeaders;
|
||||
|
||||
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,
|
||||
},
|
||||
);
|
||||
}
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 localVarHttpContext: HttpContext = options?.context ?? new HttpContext();
|
||||
|
||||
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
|
||||
if (topic) {
|
||||
topic.forEach((element) => {
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>element,
|
||||
'topic',
|
||||
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/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.');
|
||||
}
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Accept',
|
||||
localVarHttpHeaderAcceptSelected,
|
||||
);
|
||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||
if (topic) {
|
||||
topic.forEach((element) => {
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>element, 'topic');
|
||||
})
|
||||
}
|
||||
|
||||
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 =
|
||||
options?.context ?? new HttpContext();
|
||||
/**
|
||||
* Returns the nested topic hierarchy (Domains -> Fields -> Subfields -> 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> {
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
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([
|
||||
'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
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
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 -> Fields -> Subfields -> 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,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
@@ -9,18 +9,12 @@
|
||||
*/
|
||||
/* tslint:disable:no-unused-variable member-ordering */
|
||||
|
||||
import { Inject, Injectable, Optional } from '@angular/core';
|
||||
import {
|
||||
HttpClient,
|
||||
HttpHeaders,
|
||||
HttpParams,
|
||||
HttpResponse,
|
||||
HttpEvent,
|
||||
HttpParameterCodec,
|
||||
HttpContext,
|
||||
} from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
import { Inject, Injectable, Optional } from '@angular/core';
|
||||
import { HttpClient, HttpHeaders, HttpParams,
|
||||
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
|
||||
} from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
// @ts-ignore
|
||||
import { AutocompleteResponse } from '../model/autocompleteResponse';
|
||||
@@ -34,591 +28,295 @@ import { InstitutionPage } from '../model/institutionPage';
|
||||
import { InstitutionsListResponse } from '../model/institutionsListResponse';
|
||||
|
||||
// @ts-ignore
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BaseService } from '../api.base.service';
|
||||
|
||||
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class InstitutionsService extends BaseService {
|
||||
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 \'Duisburg Essen\'.
|
||||
* @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.',
|
||||
);
|
||||
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
|
||||
super(basePath, configuration);
|
||||
}
|
||||
|
||||
let localVarQueryParameters = new HttpParams({ encoder: this.encoder });
|
||||
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',
|
||||
);
|
||||
/**
|
||||
* Returns institution options for autocomplete inputs.
|
||||
* @endpoint get /api/inse-service/institutions/autocomplete
|
||||
* @param query Institution search text, for example \'Duisburg Essen\'.
|
||||
* @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 localVarHeaders = this.defaultHeaders;
|
||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||
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');
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
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/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 =
|
||||
options?.context ?? new HttpContext();
|
||||
/**
|
||||
* Returns a single institution by ID.
|
||||
* 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.');
|
||||
}
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
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([
|
||||
'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/${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`;
|
||||
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,
|
||||
},
|
||||
);
|
||||
}
|
||||
/**
|
||||
* Returns a list of OpenAlex institutions.
|
||||
* @endpoint get /api/inse-service/institutions
|
||||
* @param search Full-text search, for example \'Duisburg Essen\'.
|
||||
* @param filter OpenAlex filter, for example \'country_code:DE,type:education\'.
|
||||
* @param sort Sort field, for example \'works_count:desc\'.
|
||||
* @param groupBy OpenAlex group_by field, for example \'country_code\'.
|
||||
* @param perPage Results per page.
|
||||
* @param page Page number. Use cursor for deep pagination.
|
||||
* @param cursor Cursor pagination token. Use \'*\' 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> {
|
||||
|
||||
/**
|
||||
* Returns a single institution by ID.
|
||||
* 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 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
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
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 \'University of Duisburg Essen\'.
|
||||
* @param page Page number (0-indexed).
|
||||
* @param size Number of institutions per page.
|
||||
* @param sortBy Field to sort by, either \'relevance\', \'name\', \'works_count\', or \'citations_count\'.
|
||||
* @param sortingDirection Sorting direction, either \'asc\' or \'desc\'.
|
||||
* @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> {
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Accept',
|
||||
localVarHttpHeaderAcceptSelected,
|
||||
);
|
||||
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
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
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 \'Duisburg Essen\'.
|
||||
* @param filter OpenAlex filter, for example \'country_code:DE,type:education\'.
|
||||
* @param sort Sort field, for example \'works_count:desc\'.
|
||||
* @param groupBy OpenAlex group_by field, for example \'country_code\'.
|
||||
* @param perPage Results per page.
|
||||
* @param page Page number. Use cursor for deep pagination.
|
||||
* @param cursor Cursor pagination token. Use \'*\' 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 \'University of Duisburg Essen\'.
|
||||
* @param page Page number (0-indexed).
|
||||
* @param size Number of institutions per page.
|
||||
* @param sortBy Field to sort by, either \'relevance\', \'name\', \'works_count\', or \'citations_count\'.
|
||||
* @param sortingDirection Sorting direction, either \'asc\' or \'desc\'.
|
||||
* @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,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
@@ -9,250 +9,207 @@
|
||||
*/
|
||||
/* tslint:disable:no-unused-variable member-ordering */
|
||||
|
||||
import { Inject, Injectable, Optional } from '@angular/core';
|
||||
import {
|
||||
HttpClient,
|
||||
HttpHeaders,
|
||||
HttpParams,
|
||||
HttpResponse,
|
||||
HttpEvent,
|
||||
HttpParameterCodec,
|
||||
HttpContext,
|
||||
} from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
import { Inject, Injectable, Optional } from '@angular/core';
|
||||
import { HttpClient, HttpHeaders, HttpParams,
|
||||
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
|
||||
} from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
// @ts-ignore
|
||||
import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||
// @ts-ignore
|
||||
import { Institution } from '../model/institution';
|
||||
// @ts-ignore
|
||||
import { InstitutionPageV2 } from '../model/institutionPageV2';
|
||||
|
||||
// @ts-ignore
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BaseService } from '../api.base.service';
|
||||
|
||||
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class InstitutionsV2Service extends BaseService {
|
||||
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,
|
||||
);
|
||||
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
|
||||
super(basePath, configuration);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext =
|
||||
options?.context ?? new HttpContext();
|
||||
/**
|
||||
* 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> {
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>query, 'query');
|
||||
|
||||
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 localVarHeaders = this.defaultHeaders;
|
||||
|
||||
let localVarPath = `/api/institutions/v2/autocomplete/selector`;
|
||||
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 localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 });
|
||||
if (institutionIds) {
|
||||
institutionIds.forEach((element) => {
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>element,
|
||||
'institution_ids',
|
||||
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/autocomplete/selector`;
|
||||
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
|
||||
}
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
/**
|
||||
* Returns an institution based on its ID.
|
||||
* @endpoint get /api/institutions/v2/single/{institution_id}
|
||||
* @param institutionId The ID of the institution 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 getInstitutionById2(institutionId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Institution>;
|
||||
public getInstitutionById2(institutionId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Institution>>;
|
||||
public getInstitutionById2(institutionId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Institution>>;
|
||||
public getInstitutionById2(institutionId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (institutionId === null || institutionId === undefined) {
|
||||
throw new Error('Required parameter institutionId was null or undefined when calling getInstitutionById2.');
|
||||
}
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
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/single/${this.configuration.encodeParam({name: "institutionId", value: institutionId, 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
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext =
|
||||
options?.context ?? new HttpContext();
|
||||
/**
|
||||
* Returns a list of institutions based on their IDs.
|
||||
* @endpoint get /api/institutions/v2/multiple/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> {
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||
if (institutionIds) {
|
||||
institutionIds.forEach((element) => {
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>element, 'institution_ids');
|
||||
})
|
||||
}
|
||||
|
||||
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 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/multiple/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
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
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,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
@@ -9,18 +9,12 @@
|
||||
*/
|
||||
/* tslint:disable:no-unused-variable member-ordering */
|
||||
|
||||
import { Inject, Injectable, Optional } from '@angular/core';
|
||||
import {
|
||||
HttpClient,
|
||||
HttpHeaders,
|
||||
HttpParams,
|
||||
HttpResponse,
|
||||
HttpEvent,
|
||||
HttpParameterCodec,
|
||||
HttpContext,
|
||||
} from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
import { Inject, Injectable, Optional } from '@angular/core';
|
||||
import { HttpClient, HttpHeaders, HttpParams,
|
||||
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
|
||||
} from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
// @ts-ignore
|
||||
import { ExtractedKeywordsResponse } from '../model/extractedKeywordsResponse';
|
||||
@@ -34,250 +28,149 @@ import { PatentsByKeywordsRequest } from '../model/patentsByKeywordsRequest';
|
||||
import { PatentsByKeywordsResponse } from '../model/patentsByKeywordsResponse';
|
||||
|
||||
// @ts-ignore
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BaseService } from '../api.base.service';
|
||||
|
||||
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class KeywordsService extends BaseService {
|
||||
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.',
|
||||
);
|
||||
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
|
||||
super(basePath, configuration);
|
||||
}
|
||||
|
||||
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.');
|
||||
}
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
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;
|
||||
|
||||
|
||||
// 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 =
|
||||
options?.context ?? new HttpContext();
|
||||
/**
|
||||
* 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.');
|
||||
}
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// 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,
|
||||
);
|
||||
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
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
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,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
+533
-1123
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
@@ -9,18 +9,12 @@
|
||||
*/
|
||||
/* tslint:disable:no-unused-variable member-ordering */
|
||||
|
||||
import { Inject, Injectable, Optional } from '@angular/core';
|
||||
import {
|
||||
HttpClient,
|
||||
HttpHeaders,
|
||||
HttpParams,
|
||||
HttpResponse,
|
||||
HttpEvent,
|
||||
HttpParameterCodec,
|
||||
HttpContext,
|
||||
} from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
import { Inject, Injectable, Optional } from '@angular/core';
|
||||
import { HttpClient, HttpHeaders, HttpParams,
|
||||
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
|
||||
} from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
// @ts-ignore
|
||||
import { CreateOrganizationRequest } from '../model/createOrganizationRequest';
|
||||
@@ -34,545 +28,287 @@ import { OrganizationPage } from '../model/organizationPage';
|
||||
import { UpdateOrganizationRequest } from '../model/updateOrganizationRequest';
|
||||
|
||||
// @ts-ignore
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BaseService } from '../api.base.service';
|
||||
|
||||
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class OrganizationService extends BaseService {
|
||||
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.',
|
||||
);
|
||||
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
|
||||
super(basePath, configuration);
|
||||
}
|
||||
|
||||
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.');
|
||||
}
|
||||
|
||||
// authentication (HTTPBearer) required
|
||||
localVarHeaders = this.configuration.addCredentialToHeaders(
|
||||
'HTTPBearer',
|
||||
'Authorization',
|
||||
localVarHeaders,
|
||||
'Bearer ',
|
||||
);
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set(
|
||||
'Accept',
|
||||
localVarHttpHeaderAcceptSelected,
|
||||
);
|
||||
// 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`;
|
||||
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 =
|
||||
options?.context ?? new HttpContext();
|
||||
/**
|
||||
* Delete Organization
|
||||
* @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.');
|
||||
}
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
|
||||
// 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,
|
||||
);
|
||||
// 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
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
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';
|
||||
}
|
||||
/**
|
||||
* 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
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
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,
|
||||
},
|
||||
);
|
||||
}
|
||||
/**
|
||||
* 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.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete Organization
|
||||
* @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;
|
||||
|
||||
// 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
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
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
@@ -1,168 +0,0 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
/* tslint:disable:no-unused-variable member-ordering */
|
||||
|
||||
import { Inject, Injectable, Optional } from '@angular/core';
|
||||
import {
|
||||
HttpClient,
|
||||
HttpHeaders,
|
||||
HttpParams,
|
||||
HttpResponse,
|
||||
HttpEvent,
|
||||
HttpParameterCodec,
|
||||
HttpContext,
|
||||
} from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
// @ts-ignore
|
||||
import { CollaborationNetwork } from '../model/collaborationNetwork';
|
||||
// @ts-ignore
|
||||
import { FilterProperties } from '../model/filterProperties';
|
||||
// @ts-ignore
|
||||
import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||
|
||||
// @ts-ignore
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BaseService } from '../api.base.service';
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
})
|
||||
export class PersonNetworkService extends BaseService {
|
||||
constructor(
|
||||
protected httpClient: HttpClient,
|
||||
@Optional() @Inject(BASE_PATH) basePath: string | string[],
|
||||
@Optional() configuration?: Configuration,
|
||||
) {
|
||||
super(basePath, configuration);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a person\'s collaboration network.
|
||||
* Returns a person\'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 ??
|
||||
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/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
File diff suppressed because it is too large
Load Diff
@@ -25,6 +25,10 @@ import { Observable } from 'rxjs';
|
||||
// @ts-ignore
|
||||
import { AuthorMetricsRequest } from '../model/authorMetricsRequest';
|
||||
// @ts-ignore
|
||||
import { AuthorOrientationProfile } from '../model/authorOrientationProfile';
|
||||
// @ts-ignore
|
||||
import { AuthorOrientationProfilesRequest } from '../model/authorOrientationProfilesRequest';
|
||||
// @ts-ignore
|
||||
import { AuthorStaticStats } from '../model/authorStaticStats';
|
||||
// @ts-ignore
|
||||
import { AuthorTopicProfile } from '../model/authorTopicProfile';
|
||||
@@ -56,6 +60,137 @@ export class RankingService extends BaseService {
|
||||
super(basePath, configuration);
|
||||
}
|
||||
|
||||
/**
|
||||
* Orientation Profiles
|
||||
* Compare orientation scores for active members of the account institution.
|
||||
* @endpoint post /api/rank/orientation-profiles
|
||||
* @param authorOrientationProfilesRequest
|
||||
* @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 orientationProfilesApiRankOrientationProfilesPost(
|
||||
authorOrientationProfilesRequest: AuthorOrientationProfilesRequest,
|
||||
secureFgpAcc?: string,
|
||||
observe?: 'body',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<Array<AuthorOrientationProfile>>;
|
||||
public orientationProfilesApiRankOrientationProfilesPost(
|
||||
authorOrientationProfilesRequest: AuthorOrientationProfilesRequest,
|
||||
secureFgpAcc?: string,
|
||||
observe?: 'response',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpResponse<Array<AuthorOrientationProfile>>>;
|
||||
public orientationProfilesApiRankOrientationProfilesPost(
|
||||
authorOrientationProfilesRequest: AuthorOrientationProfilesRequest,
|
||||
secureFgpAcc?: string,
|
||||
observe?: 'events',
|
||||
reportProgress?: boolean,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<HttpEvent<Array<AuthorOrientationProfile>>>;
|
||||
public orientationProfilesApiRankOrientationProfilesPost(
|
||||
authorOrientationProfilesRequest: AuthorOrientationProfilesRequest,
|
||||
secureFgpAcc?: string,
|
||||
observe: any = 'body',
|
||||
reportProgress: boolean = false,
|
||||
options?: {
|
||||
httpHeaderAccept?: 'application/json';
|
||||
context?: HttpContext;
|
||||
transferCache?: boolean;
|
||||
},
|
||||
): Observable<any> {
|
||||
if (
|
||||
authorOrientationProfilesRequest === null ||
|
||||
authorOrientationProfilesRequest === undefined
|
||||
) {
|
||||
throw new Error(
|
||||
'Required parameter authorOrientationProfilesRequest was null or undefined when calling orientationProfilesApiRankOrientationProfilesPost.',
|
||||
);
|
||||
}
|
||||
|
||||
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/rank/orientation-profiles`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<Array<AuthorOrientationProfile>>(
|
||||
'post',
|
||||
`${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
body: authorOrientationProfilesRequest,
|
||||
responseType: <any>responseType_,
|
||||
...(withCredentials ? { withCredentials } : {}),
|
||||
headers: localVarHeaders,
|
||||
observe: observe,
|
||||
...(localVarTransferCache !== undefined
|
||||
? { transferCache: localVarTransferCache }
|
||||
: {}),
|
||||
reportProgress: reportProgress,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Rank Author
|
||||
* @endpoint post /api/rank/rank-author
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
@@ -9,250 +9,280 @@
|
||||
*/
|
||||
/* tslint:disable:no-unused-variable member-ordering */
|
||||
|
||||
import { Inject, Injectable, Optional } from '@angular/core';
|
||||
import {
|
||||
HttpClient,
|
||||
HttpHeaders,
|
||||
HttpParams,
|
||||
HttpResponse,
|
||||
HttpEvent,
|
||||
HttpParameterCodec,
|
||||
HttpContext,
|
||||
} from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
import { Inject, Injectable, Optional } from '@angular/core';
|
||||
import { HttpClient, HttpHeaders, HttpParams,
|
||||
HttpResponse, HttpEvent, HttpParameterCodec, HttpContext
|
||||
} from '@angular/common/http';
|
||||
import { CustomHttpParameterCodec } from '../encoder';
|
||||
import { Observable } from 'rxjs';
|
||||
|
||||
// @ts-ignore
|
||||
import { HTTPValidationError } from '../model/hTTPValidationError';
|
||||
// @ts-ignore
|
||||
import { SortDirection } from '../model/sortDirection';
|
||||
// @ts-ignore
|
||||
import { Topic } from '../model/topic';
|
||||
// @ts-ignore
|
||||
import { TopicPageV2 } from '../model/topicPageV2';
|
||||
// @ts-ignore
|
||||
import { TopicSortBy } from '../model/topicSortBy';
|
||||
|
||||
// @ts-ignore
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BASE_PATH, COLLECTION_FORMATS } from '../variables';
|
||||
import { Configuration } from '../configuration';
|
||||
import { BaseService } from '../api.base.service';
|
||||
|
||||
|
||||
|
||||
@Injectable({
|
||||
providedIn: 'root',
|
||||
providedIn: 'root'
|
||||
})
|
||||
export class TopicsV2Service extends BaseService {
|
||||
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,
|
||||
);
|
||||
constructor(protected httpClient: HttpClient, @Optional() @Inject(BASE_PATH) basePath: string|string[], @Optional() configuration?: Configuration) {
|
||||
super(basePath, configuration);
|
||||
}
|
||||
|
||||
const localVarHttpContext: HttpContext =
|
||||
options?.context ?? new HttpContext();
|
||||
/**
|
||||
* 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> {
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>query, 'query');
|
||||
|
||||
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 localVarHeaders = this.defaultHeaders;
|
||||
|
||||
let localVarPath = `/api/topics/v2/autocomplete/selector`;
|
||||
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 localVarHttpHeaderAcceptSelected: string | undefined = options?.httpHeaderAccept ?? this.configuration.selectHeaderAccept([
|
||||
'application/json'
|
||||
]);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
localVarHeaders = localVarHeaders.set('Accept', localVarHttpHeaderAcceptSelected);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 });
|
||||
if (topicIds) {
|
||||
topicIds.forEach((element) => {
|
||||
localVarQueryParameters = this.addToHttpParams(
|
||||
localVarQueryParameters,
|
||||
<any>element,
|
||||
'topic_ids',
|
||||
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/autocomplete/selector`;
|
||||
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
|
||||
}
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
let localVarHeaders = this.defaultHeaders;
|
||||
/**
|
||||
* Returns a topic for a given topic ID.
|
||||
* @endpoint get /api/topics/v2/single/{raw_oa_topic_id}
|
||||
* @param rawOaTopicId The ID of the topic 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 getTopicById(rawOaTopicId: string, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<Topic>;
|
||||
public getTopicById(rawOaTopicId: string, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<Topic>>;
|
||||
public getTopicById(rawOaTopicId: string, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<Topic>>;
|
||||
public getTopicById(rawOaTopicId: string, observe: any = 'body', reportProgress: boolean = false, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<any> {
|
||||
if (rawOaTopicId === null || rawOaTopicId === undefined) {
|
||||
throw new Error('Required parameter rawOaTopicId was null or undefined when calling getTopicById.');
|
||||
}
|
||||
|
||||
const localVarHttpHeaderAcceptSelected: string | undefined =
|
||||
options?.httpHeaderAccept ??
|
||||
this.configuration.selectHeaderAccept(['application/json']);
|
||||
if (localVarHttpHeaderAcceptSelected !== undefined) {
|
||||
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/single/${this.configuration.encodeParam({name: "rawOaTopicId", value: rawOaTopicId, in: "path", style: "simple", explode: false, dataType: "string", dataFormat: undefined})}`;
|
||||
const { basePath, withCredentials } = this.configuration;
|
||||
return this.httpClient.request<Topic>('get', `${basePath}${localVarPath}`,
|
||||
{
|
||||
context: localVarHttpContext,
|
||||
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.
|
||||
* @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> {
|
||||
|
||||
const localVarTransferCache: boolean = options?.transferCache ?? true;
|
||||
let localVarQueryParameters = new HttpParams({encoder: this.encoder});
|
||||
if (topicIds) {
|
||||
topicIds.forEach((element) => {
|
||||
localVarQueryParameters = this.addToHttpParams(localVarQueryParameters,
|
||||
<any>element, 'topic_ids');
|
||||
})
|
||||
}
|
||||
|
||||
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 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
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Searches for topics based on the provided criteria.
|
||||
* @endpoint get /api/topics/v2/search
|
||||
* @param searchTerm The term to search for in topic display names.
|
||||
* @param page The page number to retrieve.
|
||||
* @param size The number of topics to retrieve per page.
|
||||
* @param sortBy The field to sort by.
|
||||
* @param sortDirection The direction to sort.
|
||||
* @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 searchTopics(searchTerm?: string, page?: number, size?: number, sortBy?: TopicSortBy, sortDirection?: SortDirection, observe?: 'body', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<TopicPageV2>;
|
||||
public searchTopics(searchTerm?: string, page?: number, size?: number, sortBy?: TopicSortBy, sortDirection?: SortDirection, observe?: 'response', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpResponse<TopicPageV2>>;
|
||||
public searchTopics(searchTerm?: string, page?: number, size?: number, sortBy?: TopicSortBy, sortDirection?: SortDirection, observe?: 'events', reportProgress?: boolean, options?: {httpHeaderAccept?: 'application/json', context?: HttpContext, transferCache?: boolean}): Observable<HttpEvent<TopicPageV2>>;
|
||||
public searchTopics(searchTerm?: string, page?: number, size?: number, sortBy?: TopicSortBy, sortDirection?: SortDirection, 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>searchTerm, 'search_term');
|
||||
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>sortDirection, 'sort_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/topics/v2/search`;
|
||||
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
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
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
+171
-197
@@ -1,219 +1,193 @@
|
||||
import {
|
||||
HttpHeaders,
|
||||
HttpParams,
|
||||
HttpParameterCodec,
|
||||
} from '@angular/common/http';
|
||||
import { HttpHeaders, HttpParams, HttpParameterCodec } from '@angular/common/http';
|
||||
import { Param } from './param';
|
||||
|
||||
export interface ConfigurationParameters {
|
||||
/**
|
||||
* @deprecated Since 5.0. Use credentials instead
|
||||
*/
|
||||
apiKeys?: { [key: string]: string };
|
||||
username?: string;
|
||||
password?: string;
|
||||
/**
|
||||
* @deprecated Since 5.0. Use credentials instead
|
||||
*/
|
||||
accessToken?: string | (() => string);
|
||||
basePath?: string;
|
||||
withCredentials?: boolean;
|
||||
/**
|
||||
* Takes care of encoding query- and form-parameters.
|
||||
*/
|
||||
encoder?: HttpParameterCodec;
|
||||
/**
|
||||
* 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>.
|
||||
* <p>
|
||||
* See {@link README.md} for more details
|
||||
* </p>
|
||||
*/
|
||||
encodeParam?: (param: Param) => string;
|
||||
/**
|
||||
* The keys are the names in the securitySchemes section of the OpenAPI
|
||||
* document. They should map to the value used for authentication
|
||||
* minus any standard prefixes such as 'Basic' or 'Bearer'.
|
||||
*/
|
||||
credentials?: { [key: string]: string | (() => string | undefined) };
|
||||
/**
|
||||
* @deprecated Since 5.0. Use credentials instead
|
||||
*/
|
||||
apiKeys?: {[ key: string ]: string};
|
||||
username?: string;
|
||||
password?: string;
|
||||
/**
|
||||
* @deprecated Since 5.0. Use credentials instead
|
||||
*/
|
||||
accessToken?: string | (() => string);
|
||||
basePath?: string;
|
||||
withCredentials?: boolean;
|
||||
/**
|
||||
* Takes care of encoding query- and form-parameters.
|
||||
*/
|
||||
encoder?: HttpParameterCodec;
|
||||
/**
|
||||
* 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>.
|
||||
* <p>
|
||||
* See {@link README.md} for more details
|
||||
* </p>
|
||||
*/
|
||||
encodeParam?: (param: Param) => string;
|
||||
/**
|
||||
* The keys are the names in the securitySchemes section of the OpenAPI
|
||||
* document. They should map to the value used for authentication
|
||||
* minus any standard prefixes such as 'Basic' or 'Bearer'.
|
||||
*/
|
||||
credentials?: {[ key: string ]: string | (() => string | undefined)};
|
||||
}
|
||||
|
||||
export class Configuration {
|
||||
/**
|
||||
* @deprecated Since 5.0. Use credentials instead
|
||||
*/
|
||||
apiKeys?: { [key: string]: string };
|
||||
username?: string;
|
||||
password?: string;
|
||||
/**
|
||||
* @deprecated Since 5.0. Use credentials instead
|
||||
*/
|
||||
accessToken?: string | (() => string);
|
||||
basePath?: string;
|
||||
withCredentials?: boolean;
|
||||
/**
|
||||
* Takes care of encoding query- and form-parameters.
|
||||
*/
|
||||
encoder?: HttpParameterCodec;
|
||||
/**
|
||||
* Encoding of various path parameter
|
||||
* <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values">styles</a>.
|
||||
* <p>
|
||||
* See {@link README.md} for more details
|
||||
* </p>
|
||||
*/
|
||||
encodeParam: (param: Param) => string;
|
||||
/**
|
||||
* The keys are the names in the securitySchemes section of the OpenAPI
|
||||
* document. They should map to the value used for authentication
|
||||
* minus any standard prefixes such as 'Basic' or 'Bearer'.
|
||||
*/
|
||||
credentials: { [key: string]: string | (() => string | undefined) };
|
||||
/**
|
||||
* @deprecated Since 5.0. Use credentials instead
|
||||
*/
|
||||
apiKeys?: {[ key: string ]: string};
|
||||
username?: string;
|
||||
password?: string;
|
||||
/**
|
||||
* @deprecated Since 5.0. Use credentials instead
|
||||
*/
|
||||
accessToken?: string | (() => string);
|
||||
basePath?: string;
|
||||
withCredentials?: boolean;
|
||||
/**
|
||||
* Takes care of encoding query- and form-parameters.
|
||||
*/
|
||||
encoder?: HttpParameterCodec;
|
||||
/**
|
||||
* Encoding of various path parameter
|
||||
* <a href="https://github.com/OAI/OpenAPI-Specification/blob/main/versions/3.1.0.md#style-values">styles</a>.
|
||||
* <p>
|
||||
* See {@link README.md} for more details
|
||||
* </p>
|
||||
*/
|
||||
encodeParam: (param: Param) => string;
|
||||
/**
|
||||
* The keys are the names in the securitySchemes section of the OpenAPI
|
||||
* document. They should map to the value used for authentication
|
||||
* minus any standard prefixes such as 'Basic' or 'Bearer'.
|
||||
*/
|
||||
credentials: {[ key: string ]: string | (() => string | undefined)};
|
||||
|
||||
constructor({
|
||||
accessToken,
|
||||
apiKeys,
|
||||
basePath,
|
||||
credentials,
|
||||
encodeParam,
|
||||
encoder,
|
||||
password,
|
||||
username,
|
||||
withCredentials,
|
||||
}: ConfigurationParameters = {}) {
|
||||
if (apiKeys) {
|
||||
this.apiKeys = apiKeys;
|
||||
}
|
||||
if (username !== undefined) {
|
||||
this.username = username;
|
||||
}
|
||||
if (password !== undefined) {
|
||||
this.password = password;
|
||||
}
|
||||
if (accessToken !== undefined) {
|
||||
this.accessToken = accessToken;
|
||||
}
|
||||
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 ?? {};
|
||||
constructor({ accessToken, apiKeys, basePath, credentials, encodeParam, encoder, password, username, withCredentials }: ConfigurationParameters = {}) {
|
||||
if (apiKeys) {
|
||||
this.apiKeys = apiKeys;
|
||||
}
|
||||
if (username !== undefined) {
|
||||
this.username = username;
|
||||
}
|
||||
if (password !== undefined) {
|
||||
this.password = password;
|
||||
}
|
||||
if (accessToken !== undefined) {
|
||||
this.accessToken = accessToken;
|
||||
}
|
||||
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
|
||||
if (!this.credentials['HTTPBearer']) {
|
||||
this.credentials['HTTPBearer'] = () => {
|
||||
return typeof this.accessToken === 'function'
|
||||
? 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;
|
||||
// init default HTTPBearer credential
|
||||
if (!this.credentials['HTTPBearer']) {
|
||||
this.credentials['HTTPBearer'] = () => {
|
||||
return typeof this.accessToken === 'function'
|
||||
? this.accessToken()
|
||||
: this.accessToken;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const type = contentTypes.find((x: string) => this.isJsonMime(x));
|
||||
if (type === undefined) {
|
||||
return contentTypes[0];
|
||||
}
|
||||
return type;
|
||||
}
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Select the correct accept content-type to use for a request.
|
||||
* 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
|
||||
* @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 = contentTypes.find((x: string) => this.isJsonMime(x));
|
||||
if (type === undefined) {
|
||||
return contentTypes[0];
|
||||
}
|
||||
return type;
|
||||
}
|
||||
|
||||
const type = accepts.find((x: string) => this.isJsonMime(x));
|
||||
if (type === undefined) {
|
||||
return accepts[0];
|
||||
/**
|
||||
* Select the correct accept content-type to use for a request.
|
||||
* 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
|
||||
* @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.
|
||||
* JSON MIME examples:
|
||||
* application/json
|
||||
* application/json; charset=UTF8
|
||||
* APPLICATION/JSON
|
||||
* application/vnd.company+json
|
||||
* @param mime - MIME (Multipurpose Internet Mail Extensions)
|
||||
* @return True if the given MIME is JSON, false otherwise.
|
||||
*/
|
||||
public isJsonMime(mime: string): boolean {
|
||||
const jsonMime: RegExp = new RegExp(
|
||||
'^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$',
|
||||
'i',
|
||||
);
|
||||
return (
|
||||
mime !== null &&
|
||||
(jsonMime.test(mime) ||
|
||||
mime.toLowerCase() === 'application/json-patch+json')
|
||||
);
|
||||
}
|
||||
/**
|
||||
* Check if the given MIME is a JSON MIME.
|
||||
* JSON MIME examples:
|
||||
* application/json
|
||||
* application/json; charset=UTF8
|
||||
* APPLICATION/JSON
|
||||
* application/vnd.company+json
|
||||
* @param mime - MIME (Multipurpose Internet Mail Extensions)
|
||||
* @return True if the given MIME is JSON, false otherwise.
|
||||
*/
|
||||
public isJsonMime(mime: string): boolean {
|
||||
const jsonMime: RegExp = new RegExp('^(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 {
|
||||
const value = this.credentials[key];
|
||||
return typeof value === 'function' ? value() : value;
|
||||
}
|
||||
public lookupCredential(key: string): string | undefined {
|
||||
const value = this.credentials[key];
|
||||
return typeof value === 'function'
|
||||
? value()
|
||||
: value;
|
||||
}
|
||||
|
||||
public addCredentialToHeaders(
|
||||
credentialKey: string,
|
||||
headerName: string,
|
||||
headers: HttpHeaders,
|
||||
prefix?: string,
|
||||
): HttpHeaders {
|
||||
const value = this.lookupCredential(credentialKey);
|
||||
return value ? headers.set(headerName, (prefix ?? '') + value) : headers;
|
||||
}
|
||||
public addCredentialToHeaders(credentialKey: string, headerName: string, headers: HttpHeaders, 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 {
|
||||
const value = this.lookupCredential(credentialKey);
|
||||
return value ? query.set(paramName, value) : query;
|
||||
}
|
||||
public addCredentialToQuery(credentialKey: string, paramName: string, query: HttpParams): HttpParams {
|
||||
const value = this.lookupCredential(credentialKey);
|
||||
return value
|
||||
? query.set(paramName, value)
|
||||
: query;
|
||||
}
|
||||
|
||||
private defaultEncodeParam(param: Param): string {
|
||||
// This implementation exists as fallback for missing configuration
|
||||
// and for backwards compatibility to older typescript-angular generator versions.
|
||||
// It only works for the 'simple' parameter style.
|
||||
// Date-handling only works for the 'date-time' format.
|
||||
// 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!
|
||||
private defaultEncodeParam(param: Param): string {
|
||||
// This implementation exists as fallback for missing configuration
|
||||
// and for backwards compatibility to older typescript-angular generator versions.
|
||||
// It only works for the 'simple' parameter style.
|
||||
// Date-handling only works for the 'date-time' format.
|
||||
// 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!
|
||||
|
||||
const value =
|
||||
param.dataFormat === 'date-time' && param.value instanceof Date
|
||||
? (param.value as Date).toISOString()
|
||||
: param.value;
|
||||
const value = param.dataFormat === 'date-time' && param.value instanceof Date
|
||||
? (param.value as Date).toISOString()
|
||||
: param.value;
|
||||
|
||||
return encodeURIComponent(String(value));
|
||||
}
|
||||
return encodeURIComponent(String(value));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,16 +5,16 @@ import { HttpParameterCodec } from '@angular/common/http';
|
||||
* Workaround for https://github.com/angular/angular/issues/18261
|
||||
*/
|
||||
export class CustomHttpParameterCodec implements HttpParameterCodec {
|
||||
encodeKey(k: string): string {
|
||||
return encodeURIComponent(k);
|
||||
}
|
||||
encodeValue(v: string): string {
|
||||
return encodeURIComponent(v);
|
||||
}
|
||||
decodeKey(k: string): string {
|
||||
return decodeURIComponent(k);
|
||||
}
|
||||
decodeValue(v: string): string {
|
||||
return decodeURIComponent(v);
|
||||
}
|
||||
encodeKey(k: string): string {
|
||||
return encodeURIComponent(k);
|
||||
}
|
||||
encodeValue(v: string): string {
|
||||
return encodeURIComponent(v);
|
||||
}
|
||||
decodeKey(k: string): string {
|
||||
return decodeURIComponent(k);
|
||||
}
|
||||
decodeValue(v: string): string {
|
||||
return decodeURIComponent(v);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
@@ -9,9 +9,11 @@
|
||||
*/
|
||||
import { AccessToken } from './accessToken';
|
||||
|
||||
export interface AccessResponse {
|
||||
/**
|
||||
* The access token issued upon successful authentication.
|
||||
*/
|
||||
access_token: AccessToken;
|
||||
|
||||
export interface AccessResponse {
|
||||
/**
|
||||
* The access token issued upon successful authentication.
|
||||
*/
|
||||
access_token: AccessToken;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
@@ -10,47 +10,51 @@
|
||||
import { TokenType } from './tokenType';
|
||||
import { UserRole } from './userRole';
|
||||
|
||||
export interface AccessToken {
|
||||
/**
|
||||
* The unique identifier of the real account associated with this token.
|
||||
*/
|
||||
real_account_id: string;
|
||||
/**
|
||||
* The timestamp indicating when the token will expire.
|
||||
*/
|
||||
expires_at: string;
|
||||
/**
|
||||
* The epoch value for the token. Used for versioning of tokens.
|
||||
*/
|
||||
epoch?: number;
|
||||
/**
|
||||
* The type of the token, which is always ACCESS_TOKEN for this class.
|
||||
*/
|
||||
token_type?: TokenType;
|
||||
/**
|
||||
* A unique fingerprint of the user, used for additional security checks.
|
||||
*/
|
||||
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.
|
||||
*/
|
||||
effective_account_id: string;
|
||||
/**
|
||||
* The specific role this access token grants within its organization.
|
||||
*/
|
||||
effective_role?: UserRole;
|
||||
/**
|
||||
* The roles this access token grants within its organization.
|
||||
*/
|
||||
effective_roles?: Array<UserRole>;
|
||||
/**
|
||||
* The unique identifier of the organization associated with this access token.
|
||||
*/
|
||||
effective_organization_id: string;
|
||||
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.
|
||||
*/
|
||||
raw_token: string;
|
||||
|
||||
export interface AccessToken {
|
||||
/**
|
||||
* The unique identifier of the real account associated with this token.
|
||||
*/
|
||||
real_account_id: string;
|
||||
/**
|
||||
* The timestamp indicating when the token will expire.
|
||||
*/
|
||||
expires_at: string;
|
||||
/**
|
||||
* The epoch value for the token. Used for versioning of tokens.
|
||||
*/
|
||||
epoch?: number;
|
||||
/**
|
||||
* The type of the token, which is always ACCESS_TOKEN for this class.
|
||||
*/
|
||||
token_type?: TokenType;
|
||||
/**
|
||||
* A unique fingerprint of the user, used for additional security checks.
|
||||
*/
|
||||
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.
|
||||
*/
|
||||
effective_account_id: string;
|
||||
/**
|
||||
* The specific role this access token grants within its organization.
|
||||
*/
|
||||
effective_role?: UserRole;
|
||||
/**
|
||||
* The roles this access token grants within its organization.
|
||||
*/
|
||||
effective_roles?: Array<UserRole>;
|
||||
/**
|
||||
* The unique identifier of the organization associated with this access token.
|
||||
*/
|
||||
effective_organization_id: string;
|
||||
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.
|
||||
*/
|
||||
raw_token: string;
|
||||
}
|
||||
export namespace AccessToken {}
|
||||
export namespace AccessToken {
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
@@ -9,9 +9,11 @@
|
||||
*/
|
||||
import { AccountProfile } from './accountProfile';
|
||||
|
||||
export interface AccountPage {
|
||||
items: Array<AccountProfile>;
|
||||
total: number;
|
||||
page: number;
|
||||
page_size: number;
|
||||
|
||||
export interface AccountPage {
|
||||
items: Array<AccountProfile>;
|
||||
total: number;
|
||||
page: number;
|
||||
page_size: number;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
@@ -9,16 +9,18 @@
|
||||
*/
|
||||
import { UserRole } from './userRole';
|
||||
|
||||
export interface AccountProfile {
|
||||
id: string;
|
||||
email: string;
|
||||
name: string;
|
||||
roles: Array<UserRole>;
|
||||
organization_id: string;
|
||||
organization_name: string;
|
||||
deleted: boolean;
|
||||
activated: boolean;
|
||||
is_current?: boolean;
|
||||
is_real_account?: boolean;
|
||||
is_impersonating?: boolean;
|
||||
|
||||
export interface AccountProfile {
|
||||
id: string;
|
||||
email: string;
|
||||
name: string;
|
||||
roles: Array<UserRole>;
|
||||
organization_id: string;
|
||||
organization_name: string;
|
||||
deleted: boolean;
|
||||
activated: boolean;
|
||||
is_current?: boolean;
|
||||
is_real_account?: boolean;
|
||||
is_impersonating?: boolean;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
@@ -9,9 +9,11 @@
|
||||
*/
|
||||
import { PatentEntry } from './patentEntry';
|
||||
|
||||
export interface AllPatentsResponse {
|
||||
total: number;
|
||||
page: number;
|
||||
size: number;
|
||||
patents: Array<PatentEntry>;
|
||||
|
||||
export interface AllPatentsResponse {
|
||||
total: number;
|
||||
page: number;
|
||||
size: number;
|
||||
patents: Array<PatentEntry>;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
@@ -15,25 +15,27 @@ import { AuthorIds } from './authorIds';
|
||||
import { AuthorSummaryStats } from './authorSummaryStats';
|
||||
import { WorkTopic } from './workTopic';
|
||||
|
||||
|
||||
/**
|
||||
* A person who creates scholarly works
|
||||
*/
|
||||
export interface Author {
|
||||
id?: string | null;
|
||||
orcid?: string | null;
|
||||
display_name?: string | null;
|
||||
display_name_alternatives?: Array<string> | null;
|
||||
longest_name?: string | null;
|
||||
parsed_longest_name?: AuthorParsedLongestName | null;
|
||||
works_count?: number | null;
|
||||
cited_by_count?: number | null;
|
||||
summary_stats?: AuthorSummaryStats | null;
|
||||
affiliations?: Array<AuthorAffiliationsInner> | null;
|
||||
last_known_institutions?: Array<DehydratedInstitution> | null;
|
||||
topics?: Array<WorkTopic> | null;
|
||||
counts_by_year?: Array<AuthorCountsByYearInner> | null;
|
||||
ids?: AuthorIds | null;
|
||||
works_api_url?: string | null;
|
||||
created_date?: string | null;
|
||||
updated_date?: string | null;
|
||||
export interface Author {
|
||||
id?: string | null;
|
||||
orcid?: string | null;
|
||||
display_name?: string | null;
|
||||
display_name_alternatives?: Array<string> | null;
|
||||
longest_name?: string | null;
|
||||
parsed_longest_name?: AuthorParsedLongestName | null;
|
||||
works_count?: number | null;
|
||||
cited_by_count?: number | null;
|
||||
summary_stats?: AuthorSummaryStats | null;
|
||||
affiliations?: Array<AuthorAffiliationsInner> | null;
|
||||
last_known_institutions?: Array<DehydratedInstitution> | null;
|
||||
topics?: Array<WorkTopic> | null;
|
||||
counts_by_year?: Array<AuthorCountsByYearInner> | null;
|
||||
ids?: AuthorIds | null;
|
||||
works_api_url?: string | null;
|
||||
created_date?: string | null;
|
||||
updated_date?: string | null;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
@@ -9,10 +9,12 @@
|
||||
*/
|
||||
import { DehydratedInstitution } from './dehydratedInstitution';
|
||||
|
||||
|
||||
/**
|
||||
* AuthorAffiliationsInner
|
||||
*/
|
||||
export interface AuthorAffiliationsInner {
|
||||
institution?: DehydratedInstitution | null;
|
||||
years?: Array<number> | null;
|
||||
export interface AuthorAffiliationsInner {
|
||||
institution?: DehydratedInstitution | null;
|
||||
years?: Array<number> | null;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,18 +1,20 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* AuthorCountsByYearInner
|
||||
*/
|
||||
export interface AuthorCountsByYearInner {
|
||||
year?: number | null;
|
||||
works_count?: number | null;
|
||||
cited_by_count?: number | null;
|
||||
export interface AuthorCountsByYearInner {
|
||||
year?: number | null;
|
||||
works_count?: number | null;
|
||||
cited_by_count?: number | null;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,18 +1,20 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
* Do not edit the class manually.
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* External identifiers:
|
||||
*/
|
||||
export interface AuthorIds {
|
||||
openalex?: string | null;
|
||||
orcid?: string | null;
|
||||
scopus?: string | null;
|
||||
export interface AuthorIds {
|
||||
openalex?: string | null;
|
||||
orcid?: string | null;
|
||||
scopus?: string | null;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* Innovation Search Engine API
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
||||
* https://openapi-generator.tech
|
||||
@@ -9,14 +9,18 @@
|
||||
*/
|
||||
import { CompanyStatusFilter } from './companyStatusFilter';
|
||||
|
||||
export interface AuthorMetricsRequest {
|
||||
/**
|
||||
* OpenAlex IDs of the authors.
|
||||
*/
|
||||
author_ids: Array<string>;
|
||||
/**
|
||||
* Which companies to count for the company-foundations metric: \'all\', only \'active\' (non-deleted), or only \'deleted\'.
|
||||
*/
|
||||
company_status?: CompanyStatusFilter;
|
||||
|
||||
export interface AuthorMetricsRequest {
|
||||
/**
|
||||
* OpenAlex IDs of the authors.
|
||||
*/
|
||||
author_ids: Array<string>;
|
||||
/**
|
||||
* Which companies to count for the company-foundations metric: \'all\', only \'active\' (non-deleted), or only \'deleted\'.
|
||||
*/
|
||||
company_status?: CompanyStatusFilter;
|
||||
}
|
||||
export namespace AuthorMetricsRequest {}
|
||||
export namespace AuthorMetricsRequest {
|
||||
}
|
||||
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user