Skip to content

Commit 25fb76d

Browse files
authored
Change to module es6 (#63)
* Initial upgrade to imports * Refactoring to es6
1 parent 7cfc28c commit 25fb76d

20 files changed

+1316
-1283
lines changed

README.md

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# Library data API
22

3-
A Node JS API to provide UK public library data for library applications.
3+
An API to provide UK public library data for easy use in library applications.
44

55
## Getting Started
66

@@ -28,7 +28,7 @@ npm start
2828

2929
## Authors
3030

31-
- **Dave Rowe** - *Original code and maintenance* - [DaveBathnes](https://github.com/DaveBathnes)
31+
- **Dave Rowe** - _Original code and maintenance_ - [DaveBathnes](https://github.com/DaveBathnes)
3232

3333
See also the list of [contributors](https://github.com/LibrariesHacked/api-librarydata/contributors) who participated in this project.
3434

app.js

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,24 +1,27 @@
11
'use strict'
22

3-
const express = require('express')
4-
const app = express()
3+
import express from 'express'
4+
5+
import authenticate from './routes/authenticate.js'
6+
import libraries from './routes/libraries.js'
7+
import schemas from './routes/schemas.js'
8+
import services from './routes/services.js'
59

6-
const authenticate = require('./routes/authenticate')
7-
const libraries = require('./routes/libraries')
8-
const schemas = require('./routes/schemas')
9-
const services = require('./routes/services')
10+
import dotenv from 'dotenv'
11+
import dotenvDefaults from 'dotenv-defaults'
1012

11-
require('dotenv').config()
12-
require('dotenv-defaults').config()
13+
const app = express()
14+
dotenv.config()
15+
dotenvDefaults.config()
1316

14-
// Allow cross origin
15-
app.use(function (req, res, next) {
17+
// Allow cross origin requests
18+
app.use((req, res, next) => {
1619
res.header('Access-Control-Allow-Origin', '*')
20+
res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
1721
res.header(
1822
'Access-Control-Allow-Headers',
1923
'Origin, X-Requested-With, Content-Type, Accept, Authorization'
2024
)
21-
res.header('Access-Control-Allow-Methods', 'POST, PUT, GET, OPTIONS')
2225
next()
2326
})
2427

helpers/airtable.js

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,12 @@
1-
const Airtable = require('airtable')
1+
import Airtable from 'airtable'
22

33
/**
44
* Gets all records and fields from a table
55
* @param {string} baseName The base name e.g. librarieshacked
66
* @param {string} table The table name e.g. Library services
77
* @returns {Array} An array of records
88
*/
9-
module.exports.getAllRecordsInTable = async (baseName, table) => {
9+
export async function getAllRecordsInTable (baseName, table) {
1010
const base = new Airtable({ apiKey: process.env.AIRTABLE_API_KEY }).base(
1111
baseName
1212
)
@@ -23,7 +23,7 @@ module.exports.getAllRecordsInTable = async (baseName, table) => {
2323
* @param {string} filterFieldValue The value to filter the filter field by
2424
* @returns {Array} An array of records
2525
*/
26-
module.exports.getSingleFieldArrayAllRecordsInTable = async (
26+
export const getSingleFieldArrayAllRecordsInTable = async (
2727
baseName,
2828
table,
2929
fieldName,
@@ -56,7 +56,7 @@ module.exports.getSingleFieldArrayAllRecordsInTable = async (
5656
* @param {string} fieldValue The value to filter the filter field by
5757
* @returns
5858
*/
59-
module.exports.getRecordInTable = async (
59+
export const getRecordInTable = async (
6060
baseName,
6161
table,
6262
fieldName,

helpers/authenticate.js

Lines changed: 21 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,21 @@
1-
const pool = require('../helpers/database')
2-
const jwt = require('jsonwebtoken')
3-
const nodemailer = require('nodemailer')
4-
const Email = require('email-templates')
1+
import jsonwebtoken from 'jsonwebtoken'
2+
import { createTransport } from 'nodemailer'
3+
4+
import Email from 'email-templates'
5+
6+
import pool from '../helpers/database.js'
7+
8+
const { verify, sign } = jsonwebtoken
59

610
/**
711
* Verifies that a JWT is valid and returns the claims or null if it isn't
812
* @param {string} token A JSON web token
913
* @returns {object|null} A claims object
1014
*/
11-
module.exports.verifyToken = async token => {
15+
export const verifyToken = async token => {
1216
let domain = null
1317
try {
14-
const decoded = jwt.verify(token, process.env.AUTHSECRET)
18+
const decoded = verify(token, process.env.AUTHSECRET)
1519
domain = decoded.sub
1620
} catch (e) {
1721
return null
@@ -25,10 +29,10 @@ module.exports.verifyToken = async token => {
2529
* @param {string} token
2630
* @returns {string} Email domain
2731
*/
28-
module.exports.getTokenDomain = async token => {
32+
export const getTokenDomain = async token => {
2933
let domain = null
3034
try {
31-
const decoded = jwt.verify(token, process.env.AUTHSECRET)
35+
const decoded = verify(token, process.env.AUTHSECRET)
3236
domain = decoded.sub
3337
} catch (e) {
3438
return null
@@ -41,13 +45,14 @@ module.exports.getTokenDomain = async token => {
4145
* @param {string} domain A top level domain
4246
* @returns {object} A claims object
4347
*/
44-
module.exports.getDomainClaims = async domain => {
48+
export const getDomainClaims = async domain => {
4549
let claims = { admin: false, codes: [] }
4650
try {
4751
const query = 'select * from authentication where domain = $1 limit 1'
4852
const { rows } = await pool.query(query, [domain])
49-
if (rows.length > 0)
53+
if (rows.length > 0) {
5054
claims = { admin: rows[0].admin, codes: rows[0].authority_codes }
55+
}
5156
} catch (e) {}
5257
return claims
5358
}
@@ -58,9 +63,9 @@ module.exports.getDomainClaims = async domain => {
5863
* @param {object} claims A claims object
5964
* @param {string} website A web address domain
6065
*/
61-
module.exports.sendMagicLink = async (email, claims, website) => {
66+
export const sendMagicLink = async (email, claims, website) => {
6267
const domain = email.split('@').pop()
63-
const token = jwt.sign(claims, process.env.AUTHSECRET, {
68+
const token = sign(claims, process.env.AUTHSECRET, {
6469
audience: [website],
6570
expiresIn: '30d',
6671
issuer: 'api.librarydata.uk',
@@ -76,7 +81,7 @@ module.exports.sendMagicLink = async (email, claims, website) => {
7681
}
7782
}
7883

79-
const transporter = nodemailer.createTransport(mailConfig)
84+
const transporter = createTransport(mailConfig)
8085

8186
const emailTemplate = new Email({
8287
message: {
@@ -93,8 +98,8 @@ module.exports.sendMagicLink = async (email, claims, website) => {
9398
to: email
9499
},
95100
locals: {
96-
website: website,
97-
token: token
101+
website,
102+
token
98103
}
99104
})
100105
} catch (e) {
@@ -110,6 +115,6 @@ module.exports.sendMagicLink = async (email, claims, website) => {
110115
* @param {object} claims
111116
* @returns {boolean} Access
112117
*/
113-
module.exports.verifyServiceCodeAccess = async (serviceCode, claims) => {
118+
export const verifyServiceCodeAccess = (serviceCode, claims) => {
114119
return claims.codes.indexOf(serviceCode) === -1 && claims.admin === false
115120
}

helpers/database.js

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
1-
const pg = require('pg')
1+
import pg from 'pg'
2+
3+
const { types, Pool } = pg
24

35
// Currently using timestamp without timezone so this ensures the time isn't messed with
4-
pg.types.setTypeParser(1114, str => str)
6+
types.setTypeParser(1114, str => str)
57

8+
// This is the connection to the database
9+
// It uses the .env file to get the credentials
610
const config = {
711
user: process.env.PGUSER,
812
host: process.env.PGHOST,
@@ -16,6 +20,6 @@ const config = {
1620
idleTimeoutMillis: 30000
1721
}
1822

19-
const pool = new pg.Pool(config)
23+
const pool = new Pool(config)
2024

21-
module.exports = pool
25+
export default pool

helpers/feed.js

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
const RSSCombiner = require('../lib/feed-combiner')
1+
import RSSCombiner from '../lib/feed-combiner.js'
22

33
/**
44
* Gets a combined feed from multiple feed URLs
@@ -7,9 +7,9 @@ const RSSCombiner = require('../lib/feed-combiner')
77
* @param {Array} customNamespaces An array of namespaces
88
* @returns {Object} A combined feed
99
*/
10-
module.exports.getFeedFromUrls = async (urls, title, customNamespaces) => {
10+
export const getFeedFromUrls = async (urls, title, customNamespaces) => {
1111
const feedConfig = {
12-
title: title,
12+
title,
1313
size: 100,
1414
feeds: urls,
1515
pubDate: new Date(),
@@ -24,7 +24,7 @@ module.exports.getFeedFromUrls = async (urls, title, customNamespaces) => {
2424
* @param {string} id ID of the YouTube channel/playlist/user
2525
* @returns {string} A feed URL
2626
*/
27-
module.exports.getYouTubeFeedUrlFromId = id => {
27+
export const getYouTubeFeedUrlFromId = id => {
2828
const youTubeUrl = process.env.YOUTUBE_FEED_URL
2929
const idTypes = {
3030
UC: 'channel_id',
@@ -38,7 +38,7 @@ module.exports.getYouTubeFeedUrlFromId = id => {
3838
* @param {string} id ID of the Flickr user
3939
* @returns {string} A feed URL
4040
*/
41-
module.exports.getFlickrFeedUrlFromId = id => {
41+
export const getFlickrFeedUrlFromId = id => {
4242
return process.env.FLICKR_FEED_URL + id
4343
}
4444

@@ -47,7 +47,7 @@ module.exports.getFlickrFeedUrlFromId = id => {
4747
* @param {Array} ids An array of YouTube IDs
4848
* @returns {Array} A set of feed URLs
4949
*/
50-
module.exports.getYouTubeFeedUrlArrayFromIds = ids => {
50+
export const getYouTubeFeedUrlArrayFromIds = ids => {
5151
return ids.map(id => this.getYouTubeFeedUrlFromId(id))
5252
}
5353

@@ -56,7 +56,7 @@ module.exports.getYouTubeFeedUrlArrayFromIds = ids => {
5656
* @param {Array} ids An array of YouTube IDs
5757
* @returns {object} A combined feed
5858
*/
59-
module.exports.getFeedFromYouTubeIds = async ids => {
59+
export const getFeedFromYouTubeIds = async ids => {
6060
const urls = this.getYouTubeFeedUrlArrayFromIds(ids)
6161
const feed = await this.getFeedFromUrls(
6262
urls,
@@ -74,7 +74,7 @@ module.exports.getFeedFromYouTubeIds = async ids => {
7474
* @param {*} urls A set of Blog feed URLs
7575
* @returns {object} A combined feed
7676
*/
77-
module.exports.getFeedFromBlogUrls = async urls => {
77+
export const getFeedFromBlogUrls = async urls => {
7878
const feed = await this.getFeedFromUrls(
7979
urls,
8080
'Library blogs | Libraries at home',

helpers/github.js

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
const { Octokit } = require('@octokit/rest')
2-
const { Base64 } = require('js-base64')
1+
import { Octokit } from '@octokit/rest'
2+
import { Base64 } from 'js-base64'
33

44
/**
55
* Creates or updates a file stored in GitHub
@@ -8,13 +8,13 @@ const { Base64 } = require('js-base64')
88
* @param {string} message A commit message that describes the change
99
* @returns {boolean} Whether the update was successful.
1010
*/
11-
module.exports.createOrUpdateFile = async (
11+
export async function createOrUpdateFile (
1212
path,
1313
file,
1414
message,
1515
authorName,
1616
authorEmail
17-
) => {
17+
) {
1818
const content = Base64.encode(file)
1919

2020
const octokit = new Octokit({
@@ -26,18 +26,18 @@ module.exports.createOrUpdateFile = async (
2626

2727
const fileResult = await octokit.repos.getContent({
2828
owner: organisation,
29-
repo: repo,
29+
repo,
3030
path
3131
})
3232

3333
const sha = fileResult?.data?.sha
3434

3535
const result = await octokit.repos.createOrUpdateFileContents({
3636
owner: organisation,
37-
repo: repo,
37+
repo,
3838
path,
39-
message: message,
40-
content: content,
39+
message,
40+
content,
4141
committer: {
4242
name: process.env.GITHUB_ORGANISATION_BOT_NAME,
4343
email: process.env.GITHUB_ORGANISATION_EMAIL

helpers/schema.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
1-
const axios = require('axios')
1+
import axios from 'axios'
22

33
/**
44
* Gets the contents of a file from the URL provided
55
* @param {string} url The file URL
66
* @returns {string} The file contents
77
*/
8-
module.exports.getFileFromUrl = async url => {
8+
export const getFileFromUrl = async url => {
99
const response = await axios.get(url)
1010
return response.data
1111
}

helpers/utils.js

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,8 @@
1-
module.exports.convertJsonToGeoJson = (json, longitudeField, latitudeField) => {
1+
export const convertJsonToGeoJson = async (
2+
json,
3+
longitudeField,
4+
latitudeField
5+
) => {
26
const features = []
37
json.forEach(item => {
48
if (
@@ -7,7 +11,7 @@ module.exports.convertJsonToGeoJson = (json, longitudeField, latitudeField) => {
711
item[longitudeField] === '' ||
812
item[latitudeField] === ''
913
) {
10-
return
14+
return null
1115
} else {
1216
const feature = {
1317
type: 'Feature',

0 commit comments

Comments
 (0)