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

Bi 46 review 1 #25

Merged
merged 22 commits into from
Feb 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
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
19 changes: 17 additions & 2 deletions next.config.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,19 @@
/** @type {import('next').NextConfig} */
const nextConfig = {}
require('dotenv').config();
const nextConfig = {
async headers() {
return [
{
// matching all API routes
source: "/api/:path*",
headers: [
{ key: "Access-Control-Allow-Credentials", value: "true" },
{ key: "Access-Control-Allow-Origin", value: "*" },
{ key: "Access-Control-Allow-Methods", value: "GET,OPTIONS,PATCH,DELETE,POST,PUT" },
{ key: "Access-Control-Allow-Headers", value: "X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, X-Api-Version" },
]
}
]
}
}

module.exports = nextConfig
6 changes: 3 additions & 3 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@
"@apollo/server": "^4.9.5",
"@as-integrations/next": "^2.0.2",
"autoprefixer": "10.4.16",
"cors": "^2.8.5",
"cross-fetch": "^4.0.0",
"dotenv": "^16.3.1",
"graphql": "^16.8.1",
"graphql-tag": "^2.12.6",
"match-sorter": "^6.3.1",
Expand Down
76 changes: 36 additions & 40 deletions src/__tests__/query.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import '@testing-library/jest-dom'

import client from '../client'
import { ApolloClient, HttpLink, InMemoryCache } from '@apollo/client'

import fetch from 'cross-fetch'
import { gql } from '@apollo/client'

const query = gql`
Expand All @@ -14,48 +16,42 @@ const query = gql`
}
}
`
async function fetchData() {
try {
const result = await client.query({ query })
return result
} catch (error) {
console.error('Error in fetching college data form mongodb:', error)
}
}

let uri = 'https://web-app-client-b69l4yjrq-bacpacs-projects.vercel.app/api/graphql'
Copy link
Collaborator

Choose a reason for hiding this comment

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

Add a comment such that:

// TODO: Figure out a way to _not_ use a deployed vercel instance for GraphQL

console.log('GraphQL URI in tests:', uri)
const client = new ApolloClient({
link: new HttpLink({ uri, fetch }),
cache: new InMemoryCache(),
})
// test to check the data is not empty
test('the data is of college', async () => {
try {
const result = await fetchData()
expect(result?.data).toHaveProperty('universityList')
expect(result?.data?.universityList).toBeInstanceOf(Array)
expect(result?.data?.universityList?.length).toBeGreaterThan(0)
} catch (e) {
expect(e.message).toMatch('error')
}
const result = await client.query({ query })

expect(result?.data).not.toBeNull()
expect(result?.data).toHaveProperty('universityList')
expect(result?.data?.universityList).toBeInstanceOf(Array)
expect(result?.data?.universityList?.length).toBeGreaterThan(0)
})
// test to check the format of data recived by the query
test('the data has specific properties', async () => {
try {
const result = await fetchData()
result?.data?.universityList?.forEach((college) => {
// check for id property
expect(college).toHaveProperty('id')
expect(college?.id).not.toBeNull()
expect(typeof college?.id).toBe('string')
// check for name property
expect(college).toHaveProperty('name')
expect(college?.name).not.toBeNull()
expect(typeof college?.name).toBe('string')
// check for score property
expect(college).toHaveProperty('score')
expect(college?.score).not.toBeNull()
expect(typeof college?.score).toBe('string')
// check for country property
expect(college).toHaveProperty('country')
expect(college?.country).not.toBeNull()
expect(typeof college?.country).toBe('string')
})
} catch (e) {
expect(e.message).toMatch('error')
}
const result = await client.query({ query })

result?.data?.universityList?.forEach((college) => {
// check for id property
expect(college).toHaveProperty('id')
expect(college?.id).not.toBeNull()
expect(typeof college?.id).toBe('string')
// check for name property
expect(college).toHaveProperty('name')
expect(college?.name).not.toBeNull()
expect(typeof college?.name).toBe('string')
// check for score property
expect(college).toHaveProperty('score')
expect(college?.score).not.toBeNull()
expect(typeof college?.score).toBe('string')
// check for country property
expect(college).toHaveProperty('country')
expect(college?.country).not.toBeNull()
expect(typeof college?.country).toBe('string')
})
})
25 changes: 25 additions & 0 deletions src/__tests__/searchAlgorithm.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import searchAlgorithm from '../utils/searchAlgorithm'
describe('searchAlgorithm', () => {
const colleges = [{ name: 'Massachusetts Institute of Technology (MIT)', country: 'United States', city: 'Cambridge' }]
it('returns filtered results when input and data are provided', () => {
const input = 'mass'

const result = searchAlgorithm(input, colleges)

expect(result).toEqual([{ name: 'Massachusetts Institute of Technology (MIT)', country: 'United States', city: 'Cambridge' }])
})
it('returns an empty array when either input is not provided', () => {
const input = ''

const result = searchAlgorithm(input, colleges)

expect(result).toEqual([])
})
it('returns an empty array when either input doesnot match with the college name,city or country', () => {
const input = 'xyw'

const result = searchAlgorithm(input, colleges)

expect(result).toEqual([])
})
})
14 changes: 6 additions & 8 deletions src/app/api/graphql/route.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,15 @@ import { gql } from 'graphql-tag'
import { startServerAndCreateNextHandler } from '@as-integrations/next'

// The connection string for mongodb connection.
const uri = process.env.MONGODB_URI || 'mongodb+srv://bacpactech:[email protected]'
const uri = process.env.MONGODB_URI
const client = new MongoClient(uri)

async function getUniversityName(id) {
try {
const database = client.db('bacpac')
const universities = database.collection('universities')
const university = await universities.findOne({ id })
console.log('url', uri)
return university.name
const universityList = await universities.findOne({ id })
return universityList.name
} catch (error) {
console.log(error)
}
Expand All @@ -24,8 +23,8 @@ async function getUniversityList() {
try {
const database = client.db('bacpac')
const universities = database.collection('universities')
const university = await universities.find().toArray()
return university
const universityList = await universities.find().toArray()
return universityList
} catch (error) {
console.log('this is error from get all unversity list side', error)
}
Expand Down Expand Up @@ -57,7 +56,7 @@ const typeDefs = gql`
`

let plugins = []
const graphQLref = process.env.GRAPHQL_REF || 'bacpac-nbq1vs@current'
const graphQLref = process.env.GRAPHQL_REF
//Next.js auto assigns NODE_ENV value as development for 'next dev' command, and production for other commands
if (process.env.NODE_ENV === 'production') {
plugins = [
Expand All @@ -75,7 +74,6 @@ const server = new ApolloServer({
typeDefs,
plugins,
})

const handler = startServerAndCreateNextHandler(server)

//Exports the handler function to be used as a Next.js API route handler.
Expand Down
21 changes: 7 additions & 14 deletions src/app/page.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,27 +12,20 @@ import bacpacTitle from '../assets/bacpacTitle.png'
import bookImgLogo from '../assets/bookimg.png'
import client from '../client'
import discord from '../assets/discordLog.png'
import { gql } from '@apollo/client'
import { query } from '../queries/queries'

const query = gql`
query getUniversityList {
universityList {
id
name
score
country
city
}
}
`
export default function Home() {
const [universityData, setUniversityData] = useState(null)
const [loading, setLoading] = useState(false)
async function fetchData() {
try {
setLoading(true)
const result = await client.query({ query })
setUniversityData(result?.data?.universityList)
} catch (error) {
console.error('Error fetching data:', error)
console.log('Error fetching data:', error)
} finally {
setLoading(false)
}
}
useEffect(() => {
Expand All @@ -45,7 +38,7 @@ export default function Home() {
<div className="text-9xl font-bold mt-28">
<Image src={bacpacTitle} alt="BACPAC" className="w-full h-full" />
</div>
<SearchBar data={universityData} />
<SearchBar data={universityData} loading={loading} />
<div className="login-part w-5/12 mt-24 flex flex-col items-center">
<div className="flex items-center mb-5 w-full justify-center">
<BsStars className="text-[#6744FF] text-4xl -ml-3 center" />
Expand Down
4 changes: 3 additions & 1 deletion src/client.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@ import { ApolloClient, HttpLink, InMemoryCache } from '@apollo/client'

import fetch from 'cross-fetch'

let uri = '/api/graphql'
console.log('GraphQL URI in Client:', uri)
const client = new ApolloClient({
link: new HttpLink({ uri: 'http://localhost:3000/api/graphql', fetch }),
link: new HttpLink({ uri, fetch }),
cache: new InMemoryCache(),
})

Expand Down
5 changes: 3 additions & 2 deletions src/components/SearchBar.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import CollegeResult from '../app/components/CollegeResult'
import searchAlgorithm from '../utils/searchAlgorithm'
import { useState } from 'react'

const SearchBar = ({ data }) => {
const SearchBar = ({ data, loading }) => {
const [open, setOpen] = useState(false)
const [filterData, setFilterData] = useState([])
const handleSearch = (e) => {
Expand All @@ -13,7 +13,8 @@ const SearchBar = ({ data }) => {
setFilterData(filterData)
}
let searchResults = filterData?.map((item, index) => <CollegeResult info={item} serialNo={index} key={index} />)
if (searchResults.length === 0) searchResults = <div>No results found</div>
if (!loading && searchResults.length === 0) searchResults = <div>No results found</div>
if (loading) searchResults = <div>Loading....</div>
return (
<div className="search-box mt-4 w-5/12 h-12 rounded-2xl">
<div className="search-icon w-12 absolute h-12 flex justify-center items-center">
Expand Down
12 changes: 12 additions & 0 deletions src/queries/queries.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { gql } from '@apollo/client'
export const query = gql`
query getUniversityList {
universityList {
id
name
score
country
city
}
}
`
Loading