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

Aircraft endpoint, integration test fix #480

Open
wants to merge 21 commits into
base: master
Choose a base branch
from
Open
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
13 changes: 13 additions & 0 deletions endpoints/aircraft/documentation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Icelandic Aircraft Registry

Source: [The Icelandic Transport Authority](https://www.samgongustofa.is/flug/loftfor/loftfaraskra/)

- GET [/aircraft](https://apis.is/aircraft)

Search the Icelandic aircraft registry

| Parameters | Description | Example |
|-------------------|-----------------------------------------------------------------------|-----------------|
| Search (required) | Aircraft identification, registration number, type, owner or operator | [TF-AAC](https://apis.is/aircraft?search=TF-AAC), [1073](https://apis.is/aircraft?search=1073), [Flugfélag Íslands](https://apis.is/aircraft?search=Flugfélag+Íslands)|

---
88 changes: 88 additions & 0 deletions endpoints/aircraft/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
/* eslint-disable no-undef */
/* eslint-disable no-restricted-globals */
/* eslint-disable prefer-promise-reject-errors */
const request = require('request')
const $ = require('cheerio')
const h = require('apis-helpers')
const app = require('../../server')

const lookupAircraft = searchStr => new Promise((resolve, reject) => {
const url = `https://www.samgongustofa.is/flug/loftfor/loftfaraskra?aq=${searchStr}`
request.get({
headers: { 'User-Agent': h.browser() },
url,
}, (error, response, body) => {
if (error || response.statusCode !== 200) {
reject('www.samgongustofa.is refuses to respond or give back data')
}

const data = $(body)
const fieldList = []
data.find('.vehicleinfo ul').each((index, element) => {
const fields = []
$(element).find('li').each((i, el) => {
let val
if (i < 7) {
val = $(el).find('span').text()
} else {
// i === 7 contains info about aircraft owner
// i === 8 contains info about aircraft operator
// We'll parse these fields separately

const text = $(el).find('span').text()
const info = text.split(/\s{3,}/g)

val = {
name: info[1],
address: info[2],
locality: info[3],
country: info[4],
}
}

fields.push(val)
})

if (fields.length > 0) {
fieldList.push(fields)
}
})

if (fieldList.length > 0 && fieldList[0].length > 0) {
const aircraft = fieldList.map((fields) =>
({
id: fields[0],
registrationNumber: parseInt(fields[1], 10),
type: fields[2].replace('\t', ''),
buildYear: parseInt(fields[3], 10),
serialNumber: parseInt(fields[4], 10),
maxWeight: parseInt(fields[5], 10),
passengers: parseInt(fields[6], 10),
owner: fields[7],
operator: fields[8],
})
)

resolve(aircraft)
} else {
reject(`No aircraft found with the query ${searchStr}`)
}
})
})

app.get('/aircraft/:search?', async (req, res) => {
const search = (req.query.search || req.params.search || '').replace(' ', '+')

if (search === '') {
return res.status(400).json({ error: 'Please provide a valid search string to lookup' })
}

try {
const results = await lookupAircraft(search)
res.cache().json({ results })
} catch (error) {
res.status(500).json({ error })
}
})

module.exports = lookupAircraft
63 changes: 63 additions & 0 deletions endpoints/aircraft/tests/integration_test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/* eslint-disable import/extensions */
const fs = require('fs')
const assert = require('assert')
const nock = require('nock')
const request = require('request')
const helpers = require('../../../lib/test_helpers.js')

describe('aircraft', () => {
before(() => {
nock('https://www.samgongustofa.is')
.get('/flug/loftfor/loftfaraskra')
.query({ aq: '100' })
.reply(200, fs.readFileSync(`${__dirname}/loftfaraskra.100.fixture`))
.get('/flug/loftfor/loftfaraskra')
.query({ aq: 'loftur' })
.reply(200, fs.readFileSync(`${__dirname}/loftfaraskra.loftur.fixture`))
})

describe('correct-fields', () => {
it('should return an array of objects containing correct fields', (done) => {
const fieldsToCheckFor = [
'id',
'registrationNumber',
'type',
'buildYear',
'serialNumber',
'maxWeight',
'passengers',
'owner',
'operator',
]
const params = helpers.testRequestParams('/aircraft', { search: '100' })
const resultHandler = helpers.testRequestHandlerForFields(done, fieldsToCheckFor)
request.get(params, resultHandler)
})
})

describe('aircraft-not-found', () => {
it('should return a 404 when an aircraft is not found', (done) => {
const params = helpers.testRequestParams('/aircraft', { search: 'loftur' })
request.get(params, (error, response, body) => {
if (error) {
return done(error)
}
const json = JSON.parse(body)
assert.strictEqual(json.error, 'No aircraft found with the query loftur')
done()
})
})

it('should return a 400 when a search parameter is not provided', (done) => {
const params = helpers.testRequestParams('/aircraft')
request.get(params, (error, response, body) => {
if (error) {
return done(error)
}
const json = JSON.parse(body)
assert.strictEqual(json.error, 'Please provide a valid search string to lookup')
done()
})
})
})
})
Loading