Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FTN-58: Search by indicator id #29

Draft
wants to merge 10 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions frontend/fingertips-frontend/app/search/results/page.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { SearchResults } from '@/components/pages/search/results';
import { getSearchData } from './search-result-data';
import { getSearchService } from '@/lib/search/searchResultData';

export default async function Page(
props: Readonly<{
Expand All @@ -12,7 +12,7 @@ export default async function Page(
const indicator = searchParams?.indicator ?? '';

// Perform async API call using indicator prop
const searchResults = getSearchData();
const searchResults = await getSearchService().searchByIndicator(indicator);

return <SearchResults indicator={indicator} searchResults={searchResults} />;
}

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,15 @@ import {
} from 'govuk-react';
import { spacing, typography } from '@govuk-react/lib';

import { IndicatorSearchResult } from '@/app/search/results/search-result-data';
import { IndicatorSearchResult } from '@/lib/search/searchResultData';
import styled from 'styled-components';

type SearchResultProps = {
result: IndicatorSearchResult;
};

const StyledParagraph = styled(Paragraph)(
typography.font({ size: 19, lineHeight: '0.5' })
typography.font({ size: 19, lineHeight: '1.2' })
);

const StyledRow = styled(GridRow)(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import {
} from 'govuk-react';
import { SearchResult } from '@/components/molecules/Search/result';

import { IndicatorSearchResult } from '@/app/search/results/search-result-data';
import { IndicatorSearchResult } from '@/lib/search/searchResultData';

type SearchResultsProps = {
indicator: string;
Expand Down
56 changes: 56 additions & 0 deletions frontend/fingertips-frontend/lib/search/searchResultData.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { SearchService } from './searchService';

export interface IndicatorSearchResult {
id: string;
indicatorName: string;
latestDataPeriod?: string;
dataSource?: string;
lastUpdated?: string;
}

export interface IndicatorSearch {
searchByIndicator(indicator: string): Promise<IndicatorSearchResult[]>;
}

export const MOCK_DATA: IndicatorSearchResult[] = [
{
id: '1',
indicatorName: 'NHS',
latestDataPeriod: '2023',
dataSource: 'NHS website',
lastUpdated: formatDate(new Date('December 6, 2024')),
},
{
id: '2',
indicatorName: 'DHSC',
latestDataPeriod: '2022',
dataSource: 'Student article',
lastUpdated: formatDate(new Date('November 5, 2023')),
},
];

function formatDate(date: Date): string {
const day = String(date.getDate()).padStart(2, '0');
const month = date.toLocaleString('en-GB', { month: 'long' });
const year = date.getFullYear();

return `${day} ${month} ${year}`;
}

let searchService: SearchService;
try {
searchService = new SearchService();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If I'm understanding this correctly. This will be a singleton of the SearchService instance on the NextJS server to handle all requests. Rather than create a new instance per request. Is this the intended idea here and does this have any draw backs? Just thinking performance, load or concurrency.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure, although I did think that performing the initial set-up of the search client on each call would be a repetition of effort. My thinking was if Node is single-threaded (think it might be) then creating a new instance each time doesn't help as it's just repeated work, & if it's multi-threaded then there's nothing to stop different threads running the same function.

} catch {
// Handle error
}
gareth-allan-bjss marked this conversation as resolved.
Show resolved Hide resolved

export const getSearchService = (): IndicatorSearch => {
return searchService
? searchService
: {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
searchByIndicator(indicator: string): Promise<IndicatorSearchResult[]> {
return Promise.resolve(MOCK_DATA);
},
};
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It might be cleaner to implement this as a separate implementation of the IndicatorSearch interface.

};
62 changes: 62 additions & 0 deletions frontend/fingertips-frontend/lib/search/searchService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import { IndicatorSearch, IndicatorSearchResult } from './searchResultData';
import { AzureKeyCredential, SearchClient } from '@azure/search-documents';

type Indicator = {
IID: string;
Descriptive: {
Name: string;
Definition: string;
DataSource: string;
};
DataChange: {
LastUploadedAt: string;
};
};

const getEnvironmentVariable = (name: string): string => {
return (
process.env[name] ??
(() => {
throw new Error(`Missing environment variable ${name}`);
})()
);
};
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This might make more sense in its own file, as I expect we'll want to use it from other places.


export class SearchService implements IndicatorSearch {
readonly searchClient: SearchClient<Indicator>;

constructor() {
const serviceName = getEnvironmentVariable('DHSC_AI_SEARCH_SERVICE_NAME');
const indexName = getEnvironmentVariable('DHSC_AI_SEARCH_INDEX_NAME');
const apiKey = getEnvironmentVariable('DHSC_AI_SEARCH_API_KEY');

this.searchClient = new SearchClient<Indicator>(
`https://${serviceName}.search.windows.net`,
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I appreciate this was how I did it in the PoC, but I think we're probably better taking the full URL to the search service as an environment variable (e.g. https://<serviceName>.search.windows.net), as it means we're not baking in knowledge of the AI search URL structure to our code.

indexName,
new AzureKeyCredential(apiKey)
);
}

async searchByIndicator(indicator: string): Promise<IndicatorSearchResult[]> {
const query = `/.*${indicator}.*/`;

const searchResponse = await this.searchClient.search(query, {
queryType: 'full',
gareth-allan-bjss marked this conversation as resolved.
Show resolved Hide resolved
searchFields: ['IID'],
includeTotalCount: true,
});

const results: IndicatorSearchResult[] = [];
for await (const result of searchResponse.results) {
results.push({
id: result?.document?.IID,
indicatorName: result?.document?.Descriptive?.Name,
latestDataPeriod: undefined,
dataSource: result.document?.Descriptive?.DataSource,
lastUpdated: result.document?.DataChange?.LastUploadedAt,
});
}

return results;
}
}
Loading
Loading