Skip to content

Commit

Permalink
refactor: replace moment with luxon
Browse files Browse the repository at this point in the history
  • Loading branch information
frytg committed Mar 15, 2023
1 parent b4c5035 commit 4eca893
Show file tree
Hide file tree
Showing 16 changed files with 215 additions and 161 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- feat: enable multiple user accounts for DTS plugin
- refactor: move DTS keys from GCP Secrets to env
- refactor: move some event functions to utils
- refactor: replace `moment` with `luxon`

## [1.4.1] - 2022-12-23

Expand Down
20 changes: 10 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,15 @@ These ARD broadcasters are currently sending live metadata via ARD Eventhub:

| Broadcaster | TEST | PROD |
| ---------------- | ---- | ---- |
| BR | | |
| HR | | |
| MDR | - | |
| NDR | | |
| Radio Bremen | - | |
| RBB | - | |
| SR | - | |
| SWR | | |
| WDR | | |
| BR |||
| HR |||
| MDR | - ||
| NDR |||
| Radio Bremen | - ||
| RBB | - ||
| SR | - ||
| SWR |||
| WDR |||
| Deutschlandradio | - | - |

## Get Started and Documentation
Expand Down Expand Up @@ -82,7 +82,7 @@ This source code is provided under EUPL v1.2, except for the [`spdx-exceptions`]
| NPM | `firebase-admin` | [Apache License 2.0](https://github.com/firebase/firebase-admin-node/blob/master/LICENSE) |
| NPM | `google-auth-library` | [Apache License 2.0](https://github.com/googleapis/google-auth-library-nodejs/blob/master/LICENSE) |
| NPM | `jsonwebtoken` | [MIT](https://github.com/auth0/node-jsonwebtoken/blob/master/LICENSE) |
| NPM | `moment` | [MIT](https://github.com/moment/moment/blob/develop/LICENSE) |
| NPM | `luxon` | [MIT](https://github.com/moment/luxon/blob/master/LICENSE.md) |
| NPM | `slug` | [MIT](https://github.com/Trott/slug/blob/master/LICENSE) |
| NPM | `swagger-ui-express` | [MIT](https://github.com/scottie1984/swagger-ui-express/blob/master/LICENSE) |
| NPM | `uuid` | [MIT](https://github.com/uuidjs/uuid/blob/master/LICENSE.md) |
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
"firebase-admin": "11.5.0",
"google-auth-library": "8.7.0",
"jsonwebtoken": "9.0.0",
"moment": "2.29.4",
"luxon": "^3.3.0",
"slug": "8.2.2",
"swagger-ui-express": "4.6.2",
"uuid": "9.0.0",
Expand Down
6 changes: 4 additions & 2 deletions src/ingest/auth/login/post.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/

// load node utils
const moment = require('moment')
const { DateTime } = require('luxon')

// load eventhub utils
const firebase = require('../../../utils/firebase')
Expand All @@ -29,7 +29,9 @@ module.exports = async (req, res) => {
// return ok
return response.ok(req, res, {
expiresIn: parseInt(login.login.expiresIn),
expires: moment().add(parseInt(login.login.expiresIn), 's').toISOString(),
expires: DateTime.now()
.plus({ seconds: parseInt(login.login.expiresIn) })
.toISO(),

token: login.login.idToken,
refreshToken: login.login.refreshToken,
Expand Down
6 changes: 4 additions & 2 deletions src/ingest/auth/refresh/post.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/

// load node utils
const moment = require('moment')
const { DateTime } = require('luxon')

// load eventhub utils
const firebase = require('../../../utils/firebase')
Expand All @@ -29,7 +29,9 @@ module.exports = async (req, res) => {
// return ok
return response.ok(req, res, {
expiresIn: parseInt(login.login.expires_in),
expires: moment().add(parseInt(login.login.expires_in), 's').toISOString(),
expires: DateTime.now()
.plus({ seconds: parseInt(login.login.expires_in) })
.toISO(),

token: login.login.id_token,
refreshToken: login.login.refresh_token,
Expand Down
134 changes: 6 additions & 128 deletions src/ingest/events/post.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,11 @@
*/

// load node utils
const moment = require('moment')
const { createHashedId } = require('@swrlab/utils/packages/ard')
const { DateTime } = require('luxon')

// load eventhub utils
const core = require('../../utils/core')
const datastore = require('../../utils/datastore')
const { createNewTopic, processServices } = require('../../utils/events')
const logger = require('../../utils/logger')
const pubsub = require('../../utils/pubsub')
const response = require('../../utils/response')
Expand All @@ -20,73 +19,6 @@ const response = require('../../utils/response')
const config = require('../../../config')

const source = 'ingest/events/post'
const urnPublisherRegex = /(?=urn:ard:publisher:[a-z0-9]{16})/g

const processServices = async (service, req) => {
// fetch prefix from configured list
const urnPrefix = config.coreIdPrefixes[service.type]
const topicId = `${urnPrefix}${createHashedId(service.externalId)}`

// create hash based on prefix and id
service.topic = {
id: topicId,

// create pub/sub-compliant name
name: pubsub.buildId(service.topic.id),
}

// convert publisher if not in new urn format
if (!service.publisherId.match(urnPublisherRegex)) {
// fetch prefix
const urnPublisherPrefix = config.coreIdPrefixes.Publisher

// add trailing 0 if number is only 5 digits
if (service.publisherId.length === 5) service.publisherId = `${service.publisherId}0`

// create hash using given publisherId
service.publisherId = `${urnPublisherPrefix}${createHashedId(service.publisherId)}`
}

// fetch publisher
const publisher = await core.getPublisher(service.publisherId)

// block access if publisher not found
if (!publisher) {
// set blocked flag to be filtered out
service.blocked = `Publisher not found > ${service.publisherId}`

// log access attempt
logger.log({
level: 'warning',
message: service.blocked,
source,
data: { service, user: req.user },
})

// stop processing
return service
}

// check allowed institutions for current user
if (req.user.institutionId !== publisher?.institution?.id) {
// set blocked flag to be filtered out
service.blocked = 'User unauthorized for service'

// log access attempt
logger.log({
level: 'warning',
message: service.blocked,
source,
data: { service, user: req.user, publisher: publisher?.institution },
})

// stop processing
return service
}

// final data
return service
}

module.exports = async (req, res) => {
try {
Expand All @@ -99,7 +31,7 @@ module.exports = async (req, res) => {
}

// check offset for start event
if (moment(req.body.start).add(2, 'm').isBefore()) {
if (DateTime.now() > DateTime.fromISO(req.body.start).plus({ minutes: 2 })) {
return response.errors.expiredStartTime(req, res)
}

Expand All @@ -109,7 +41,7 @@ module.exports = async (req, res) => {
const message = {
name: eventName,
creator: req.user.email,
created: moment().toISOString(),
created: DateTime.now().toUTC().toISO(),

// use entire POST body to include potentially new fields
...req.body,
Expand All @@ -121,7 +53,6 @@ module.exports = async (req, res) => {
// save message to datastore
const savedMessage = await datastore.save(message, 'events')
message.id = savedMessage.id.toString()
delete message.creator

// collect unknown topics from returning errors
const newServices = []
Expand All @@ -137,61 +68,8 @@ module.exports = async (req, res) => {
service.topic.status = 'TOPIC_ERROR'
service.topic.messageId = null
} else if (messageId === 'TOPIC_NOT_FOUND') {
// fetch publisher
const publisher = await core.getPublisher(service.publisherId)

// try creating new topic
const newTopic = {
created: moment().toISOString(),
creator: req.user.email,

coreId: service.topic.id,
externalId: service.externalId,
name: service.topic.name,

institution: {
id: req.user.institutionId,
title: publisher.institution.title,
},

publisher: {
id: service.publisherId,
title: publisher.title,
},
}

// save topic to datastore
await datastore.save(newTopic, 'topics')
newTopic.id = newTopic.id.toString()

// create topic
const [result] = await pubsub.createTopic(newTopic)

// handle feedback
if (result?.name?.indexOf(service.topic.name) !== -1) {
// update api result that topic was created
service.topic.status = 'TOPIC_CREATED'

logger.log({
level: 'notice',
message: `topic created > ${service.topic.name}`,
source,
data: { service, result },
})
} else {
// update api result that topic was not created
service.topic.status = 'TOPIC_NOT_CREATED'

logger.log({
level: 'error',
message: `failed creating topic > ${service.topic.name}`,
source,
data: { service, result },
})
}

// insert empty id
service.topic.messageId = null
// first message, create a new topic
service.topic = await createNewTopic(service, req)
} else {
// insert messageId
service.topic.status = 'MESSAGE_SENT'
Expand Down
4 changes: 2 additions & 2 deletions src/ingest/router.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

// import express.router
const express = require('express')
const moment = require('moment')
const { DateTime } = require('luxon')
const OpenApiValidator = require('express-openapi-validator')

// load swagger UI
Expand All @@ -34,7 +34,7 @@ router.use(
{
name: 'iso8601-timestamp',
type: 'string',
validate: (value) => moment(value, moment.ISO_8601).isValid(),
validate: (value) => DateTime.fromISO(value).isValid(),
},
],
})
Expand Down
4 changes: 2 additions & 2 deletions src/ingest/subscriptions/post.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
*/

// load node utils
const moment = require('moment')
const { DateTime } = require('luxon')
const { v4: uuidv4 } = require('uuid')

// load eventhub utils
Expand Down Expand Up @@ -69,7 +69,7 @@ module.exports = async (req, res) => {

creator: req.user.email,
institutionId: req.user.institutionId,
created: moment().toISOString(),
created: DateTime.now().toUTC().toISO(),
}

// save to datastore
Expand Down
77 changes: 77 additions & 0 deletions src/utils/events/createNewTopic.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
/*
ard-eventhub
by SWR Audio Lab
*/

// load node utils
const { DateTime } = require('luxon')

// load eventhub utils
const core = require('../core')
const datastore = require('../datastore')
const logger = require('../logger')
const pubsub = require('../pubsub')

const source = 'utils.events.createNewTopic'

module.exports = async (service, req) => {
// fetch publisher
const publisher = await core.getPublisher(service.publisherId)

// try creating new topic
const newTopic = {
created: DateTime.now().toUTC().toISO(),
creator: req.user.email,

coreId: service.topic.id,
externalId: service.externalId,
name: service.topic.name,

institution: {
id: req.user.institutionId,
title: publisher.institution.title,
},

publisher: {
id: service.publisherId,
title: publisher.title,
},
}

// save topic to datastore
await datastore.save(newTopic, 'topics')
newTopic.id = newTopic.id.toString()

// create topic
const [result] = await pubsub.createTopic(newTopic)

// handle feedback
if (result?.name?.indexOf(service.topic.name) !== -1) {
// update api result that topic was created
service.topic.status = 'TOPIC_CREATED'

logger.log({
level: 'notice',
message: `topic created > ${service.topic.name}`,
source,
data: { service, result },
})
} else {
// update api result that topic was not created
service.topic.status = 'TOPIC_NOT_CREATED'

logger.log({
level: 'error',
message: `failed creating topic > ${service.topic.name}`,
source,
data: { service, result },
})
}

// insert empty id
service.topic.messageId = null

return Promise.resolve(service.topic)
}
14 changes: 14 additions & 0 deletions src/utils/events/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/*
ard-eventhub
by SWR Audio Lab
*/

const createNewTopic = require('./createNewTopic')
const processServices = require('./processServices')

module.exports = {
createNewTopic,
processServices,
}
Loading

0 comments on commit 4eca893

Please sign in to comment.