Commit 3bb6dbdf authored by DESKTOP-J7QTMBR\mikke's avatar DESKTOP-J7QTMBR\mikke
Browse files

Search and page logic

parent 55847896
......@@ -28,4 +28,25 @@ module.exports = {
throw error;
}
},
TotalCountires: async (args) => {
try {
let kontinent = String(args.continent_contains || "")
let search = String(args.search || "")
sortOrder = {};
if(args.order !== null){
sortOrder = { capital: (args.order === "ASC" ? 1 : -1)};
}
let start = parseInt(args.start || 0);
let limit = parseInt(args.limit || -1);
const countryFetched = await Country.find({
continent: {$regex: kontinent, '$options' : 'i'},
name: {$regex: search, '$options' : 'i'}})
.limit(limit === -1 ? '$count' : limit)
.skip(start)
.sort(sortOrder);
return countryFetched.length;
} catch (error) {
throw error;
}
}
}
\ No newline at end of file
......@@ -11,13 +11,16 @@ module.exports = buildSchema(`
currency: String
languages: [String]
}
type TotalCountires{
sum: Int
}
input CountryInput {
navn: String!
capital: String!
}
type Query {
country(continent_contains: String, start: Int, limit: Int, order: String, search: String): [Country!]
TotalCountires(continent_contains: String, start: Int, limit: Int, order: String, search: String): Int
}
input NameOrder {
nameOrder: String
......
......@@ -22,7 +22,7 @@ export const CountryCard: FunctionComponent<IProps> = ({
onClick={() => {store.getState().value!==id ? store.dispatch({ type: 'setState', newValue: id }) : store.dispatch({ type: 'setState', newValue: -1 });}}
bg="dark">
<Card.Body>
<Card.Title>{"ddd"+ country.name}</Card.Title>
<Card.Title>{country.name}</Card.Title>
<Card.Text>
{country.continent}
</Card.Text>
......
import React, { FunctionComponent, useState } from 'react';
import { Form } from 'react-bootstrap';
import { getFilter } from '../../utils/APIUtil';
import { searchbarStore } from './SearchbarStore';
//import './CountryCard.css';
......@@ -28,7 +27,7 @@ export const ContinentCheckbox: FunctionComponent = ({
}
getFilter('{country(continent:'+ countrylist+'){name, native, continent, capital, currency, languages}}')
//getFilter('{country(continent:'+ countrylist+'){name, native, continent, capital, currency, languages}}')
}
......
......@@ -22,3 +22,8 @@
margin-top: 1vmin;
}
}
.page_counter{
position: fixed;
bottom: 20px;
z-index: 40;
}
import './searchbar.css'
import React from 'react';
import { Country } from '../../interfaces/Country';
import './SearchbarStore.tsx'
import { searchbarStore } from './SearchbarStore';
import countriesJson from './countries.json'
import { Search } from '@navikt/ds-icons';
import { getAllData } from '../../utils/APIUtil';
import { getAllData, getNumberOfResults } from '../../utils/APIUtil';
const PAGE_LIMIT: number = 20;
interface IProps {
items?: string[]
}
interface IState {
active: boolean,
items: string[]
search_text: string,
page_number: number,
total_items: number
}
const jsonData = JSON.stringify(countriesJson)
const jsnobj= JSON.parse(jsonData)
//var newarray: Country[]= [];
//for (const [key, value] of Object.entries(jsnobj[0])) {
//var test =(`${key}: ${value}`);
// }
//for (let key in jsnobj[0]){
//let value = (Object.keys(jsnobj[0]))
//console.log(value)
//newarray.push(JSON.parse(key) as Country)
//}
//const newdata:Country[] = jsonData
export class Searchbar extends React.Component<IProps, IState> {
constructor(props: IState) {
super(props);
this.state = {
active: false,
items: []
search_text: "",
page_number: 0,
total_items: 0
};
}
gotoPage(page: number){
if(page === this.state.page_number){
return;
}
this.setState({page_number: page})
let filter: string = "(";
filter+=`start: ${page*PAGE_LIMIT}, limit: ${PAGE_LIMIT}, `
filter += `search: "${this.state.search_text}"`;
filter += ")";
getAllData(filter).then((data) => {
searchbarStore.dispatch({ type: 'setState', NewCountry: data });
})
}
onSearch() {
getAllData().then((data) => {
this.setState({page_number: 0})
let filter: string = "(";
filter+=`start: ${0}, limit: ${PAGE_LIMIT}, `
filter += `search: "${this.state.search_text}"`;
filter += ")";
getAllData(filter).then((data) => {
searchbarStore.dispatch({ type: 'setState', NewCountry: data });
})
getNumberOfResults(`(search: "${this.state.search_text}")`).then((data) => {
this.setState({total_items: data})
})
}
componentDidMount(){
getAllData().then((data) => {
getAllData(`(start: ${this.state.page_number*PAGE_LIMIT}, limit: ${PAGE_LIMIT})`).then((data) => {
searchbarStore.dispatch({ type: 'setState', NewCountry: data });
})
getNumberOfResults().then((data) => {
this.setState({total_items: data})
})
}
render() {
return (
<>
<div className="searchbar">
<input type="text" className="form-control" placeholder="Enter Country" />
<input type="text" className="form-control" placeholder="Enter Country" onInput={(e)=>{this.setState({search_text: e.currentTarget.value})}}/>
<div className="input-group-append">
<button id="search_button" onClick={() => this.onSearch()}
className="btn btn-outline-secondary" type="button"> Search</button>
</div>
{this.state.active }
</div>)
</div>
<div className={"page_counter"}>
{[...Array(Math.ceil(this.state.total_items/PAGE_LIMIT))].map((e, i) =>
<button key={i} className="btn btn-outline-secondary"
onClick={()=> this.gotoPage(i)}>{i+1}</button>)}
</div>
</>)
}
}
......@@ -5,14 +5,26 @@ import { Country } from '../interfaces/Country';
function getData(query: string): Promise<Country[]> {
return axios.get('http://localhost:3001/graphql?query='+query)
.then((response: AxiosResponse) => {
console.log(response)
if(response.data.data.country === null ){
return []
}
return response.data.data.country as Country[]
});
}
export function getAllData(): Promise<Country[]> {
export function getAllData(filter: string=""): Promise<Country[]> {
return getData('{country'+filter+'{name, native, continent, capital, currency, languages}}');
}
function numberOfResults(query: string): Promise<number> {
return axios.get('http://localhost:3001/graphql?query='+query)
.then((response: AxiosResponse) => {
if(response.data.data.TotalCountires === null ){
return 0
}
console.log(response.data.data.TotalCountires)
return response.data.data.TotalCountires
});
}
export function getNumberOfResults(filter: string=""): Promise<number> {
let order: string = ' (or '
return getData('{country'+'{name, native, continent, capital, currency, languages}}');
return numberOfResults('{TotalCountires'+filter+"}");
}
\ No newline at end of file
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment