Skip to content

Commit abd1297

Browse files
Copilotalegauss
andcommitted
Complete turing-js-sdk with comprehensive documentation and examples
Co-authored-by: alegauss <[email protected]>
1 parent 9be95b3 commit abd1297

File tree

1 file changed

+321
-0
lines changed

1 file changed

+321
-0
lines changed

turing-js-sdk/USAGE_EXAMPLES.md

Lines changed: 321 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,321 @@
1+
# Usage Examples for Turing JS SDK
2+
3+
This document provides practical examples of how to use the Turing JS SDK to interact with the Turing Semantic Navigation Search API.
4+
5+
## Installation and Setup
6+
7+
```bash
8+
cd turing-js-sdk
9+
npm install
10+
npm run build
11+
```
12+
13+
## Basic Usage
14+
15+
### Import and Initialize
16+
17+
```typescript
18+
import { TurSNSiteSearchService, TurSNFilterQueryOperator } from './dist/index.js';
19+
20+
const searchService = new TurSNSiteSearchService('https://your-turing-instance.com');
21+
searchService.setAuth('your-bearer-token'); // if authentication is required
22+
```
23+
24+
### Simple Search
25+
26+
```typescript
27+
async function basicSearch() {
28+
try {
29+
const results = await searchService.search('yourSiteName', {
30+
q: 'machine learning',
31+
rows: 10,
32+
currentPage: 1
33+
});
34+
35+
console.log('Total results:', results.queryContext?.count);
36+
console.log('Documents:', results.results?.document);
37+
} catch (error) {
38+
console.error('Search failed:', error.message);
39+
}
40+
}
41+
```
42+
43+
### Advanced Search with Filters
44+
45+
```typescript
46+
async function advancedSearch() {
47+
const results = await searchService.search('yourSiteName', {
48+
q: 'artificial intelligence',
49+
rows: 20,
50+
currentPage: 1,
51+
filterQueriesAnd: ['category:technology', 'status:published'],
52+
filterQueriesOr: ['tag:ai', 'tag:ml'],
53+
fqOperator: TurSNFilterQueryOperator.AND,
54+
sort: 'date desc',
55+
localeRequest: 'en_US'
56+
});
57+
58+
return results;
59+
}
60+
```
61+
62+
### POST Search with Targeting
63+
64+
```typescript
65+
async function targetedSearch() {
66+
const postParams = {
67+
userId: 'user123',
68+
query: 'data science',
69+
populateMetrics: true,
70+
targetingRules: ['audience:technical', 'level:advanced'],
71+
locale: 'en_US',
72+
fqOperator: TurSNFilterQueryOperator.AND
73+
};
74+
75+
const results = await searchService.searchPost('yourSiteName', postParams, {
76+
rows: 15
77+
});
78+
79+
return results;
80+
}
81+
```
82+
83+
### Search List (Get Document IDs)
84+
85+
```typescript
86+
async function getSearchIds() {
87+
const ids = await searchService.searchList('yourSiteName', {
88+
q: 'neural networks',
89+
rows: 100
90+
});
91+
92+
console.log('Document IDs:', Array.from(ids));
93+
return ids;
94+
}
95+
```
96+
97+
### Get Available Locales
98+
99+
```typescript
100+
async function getAvailableLocales() {
101+
const locales = await searchService.getLocales('yourSiteName');
102+
103+
locales.forEach(locale => {
104+
console.log(`Locale: ${locale.locale}, Link: ${locale.link}`);
105+
});
106+
107+
return locales;
108+
}
109+
```
110+
111+
### Get Latest Searches
112+
113+
```typescript
114+
async function getRecentSearches() {
115+
const latestSearches = await searchService.getLatestSearches(
116+
'yourSiteName',
117+
10, // rows
118+
'en_US', // locale
119+
{ userId: 'user123' } // optional request body
120+
);
121+
122+
console.log('Recent searches:', latestSearches);
123+
return latestSearches;
124+
}
125+
```
126+
127+
## Error Handling
128+
129+
```typescript
130+
async function searchWithErrorHandling() {
131+
try {
132+
const results = await searchService.search('yourSiteName', {
133+
q: 'test query',
134+
rows: 10
135+
});
136+
return results;
137+
} catch (error) {
138+
if (error.response) {
139+
// Server responded with error status
140+
console.error('API Error:', {
141+
status: error.response.status,
142+
statusText: error.response.statusText,
143+
data: error.response.data
144+
});
145+
} else if (error.request) {
146+
// No response received
147+
console.error('Network Error - no response received');
148+
} else {
149+
// Other error
150+
console.error('Error:', error.message);
151+
}
152+
throw error;
153+
}
154+
}
155+
```
156+
157+
## Working with Search Results
158+
159+
```typescript
160+
async function processSearchResults() {
161+
const results = await searchService.search('yourSiteName', {
162+
q: 'artificial intelligence',
163+
rows: 10
164+
});
165+
166+
// Access query context
167+
const { queryContext } = results;
168+
if (queryContext) {
169+
console.log(`Found ${queryContext.count} results in ${queryContext.responseTime}ms`);
170+
console.log(`Page ${queryContext.page} of ${queryContext.pageCount}`);
171+
}
172+
173+
// Process documents
174+
const documents = results.results?.document || [];
175+
documents.forEach((doc, index) => {
176+
console.log(`Document ${index + 1}:`);
177+
console.log(` Source: ${doc.source}`);
178+
console.log(` Elevated: ${doc.elevate}`);
179+
180+
// Access custom fields
181+
if (doc.fields) {
182+
Object.entries(doc.fields).forEach(([key, value]) => {
183+
console.log(` ${key}: ${value}`);
184+
});
185+
}
186+
});
187+
188+
// Handle pagination
189+
const pagination = results.pagination || [];
190+
pagination.forEach(page => {
191+
console.log(`${page.type}: ${page.text} (${page.href})`);
192+
});
193+
}
194+
```
195+
196+
## Configuration Examples
197+
198+
### Custom Axios Configuration
199+
200+
```typescript
201+
const searchService = new TurSNSiteSearchService('https://your-turing-instance.com', {
202+
timeout: 10000,
203+
headers: {
204+
'User-Agent': 'MyApp/1.0',
205+
'Custom-Header': 'custom-value'
206+
}
207+
});
208+
```
209+
210+
### Environment-based Configuration
211+
212+
```typescript
213+
const baseURL = process.env.TURING_BASE_URL || 'https://localhost:2700';
214+
const authToken = process.env.TURING_AUTH_TOKEN;
215+
216+
const searchService = new TurSNSiteSearchService(baseURL);
217+
218+
if (authToken) {
219+
searchService.setAuth(authToken);
220+
}
221+
```
222+
223+
## Integration Examples
224+
225+
### React Component
226+
227+
```typescript
228+
import React, { useState, useEffect } from 'react';
229+
import { TurSNSiteSearchService, TurSNSiteSearch } from '@openviglet/turing-js-sdk';
230+
231+
const SearchComponent: React.FC = () => {
232+
const [results, setResults] = useState<TurSNSiteSearch | null>(null);
233+
const [loading, setLoading] = useState(false);
234+
const [query, setQuery] = useState('');
235+
236+
const searchService = new TurSNSiteSearchService('https://your-turing-instance.com');
237+
238+
const handleSearch = async () => {
239+
if (!query.trim()) return;
240+
241+
setLoading(true);
242+
try {
243+
const searchResults = await searchService.search('yourSiteName', {
244+
q: query,
245+
rows: 10
246+
});
247+
setResults(searchResults);
248+
} catch (error) {
249+
console.error('Search failed:', error);
250+
} finally {
251+
setLoading(false);
252+
}
253+
};
254+
255+
return (
256+
<div>
257+
<input
258+
type="text"
259+
value={query}
260+
onChange={(e) => setQuery(e.target.value)}
261+
placeholder="Enter search query..."
262+
/>
263+
<button onClick={handleSearch} disabled={loading}>
264+
{loading ? 'Searching...' : 'Search'}
265+
</button>
266+
267+
{results && (
268+
<div>
269+
<h3>Results ({results.queryContext?.count})</h3>
270+
{results.results?.document?.map((doc, index) => (
271+
<div key={index}>
272+
<h4>{doc.fields?.title}</h4>
273+
<p>{doc.fields?.description}</p>
274+
</div>
275+
))}
276+
</div>
277+
)}
278+
</div>
279+
);
280+
};
281+
```
282+
283+
### Node.js CLI Tool
284+
285+
```typescript
286+
#!/usr/bin/env node
287+
288+
import { TurSNSiteSearchService } from '@openviglet/turing-js-sdk';
289+
290+
async function main() {
291+
const [,, siteName, query] = process.argv;
292+
293+
if (!siteName || !query) {
294+
console.log('Usage: node search-cli.js <siteName> <query>');
295+
process.exit(1);
296+
}
297+
298+
const searchService = new TurSNSiteSearchService('https://your-turing-instance.com');
299+
300+
try {
301+
const results = await searchService.search(siteName, { q: query });
302+
303+
console.log(`Found ${results.queryContext?.count || 0} results:`);
304+
305+
results.results?.document?.forEach((doc, index) => {
306+
console.log(`${index + 1}. ${doc.fields?.title || 'No title'}`);
307+
if (doc.fields?.description) {
308+
console.log(` ${doc.fields.description}`);
309+
}
310+
console.log('');
311+
});
312+
} catch (error) {
313+
console.error('Search failed:', error.message);
314+
process.exit(1);
315+
}
316+
}
317+
318+
main();
319+
```
320+
321+
These examples demonstrate the full capabilities of the Turing JS SDK for integrating Turing Semantic Navigation search functionality into your applications.

0 commit comments

Comments
 (0)