Skip to content

Commit

Permalink
Merge pull request #106 from microlinkhq/next
Browse files Browse the repository at this point in the history
fix: ensure scripts are present
  • Loading branch information
Kikobeats authored Oct 1, 2022
2 parents dc64a2d + fd570f0 commit a4c8d2f
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 6 deletions.
24 changes: 18 additions & 6 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,17 @@ const TYPE = {
TRACK: 'track'
}

const ERROR = {
REPORT:
'Please report the problem at https://github.com/microlinkhq/spotify-url-info/issues.',
NOT_DATA: "Couldn't find any data in embed page that we know how to parse.",
NOT_SCRIPTS: "Couldn't find scripts to get the data."
}

const throwError = message => {
throw new TypeError(`${message}\n${ERROR.REPORT}`)
}

const SUPPORTED_TYPES = Object.values(TYPE)

const createGetData = fetch => async (url, opts) => {
Expand All @@ -21,9 +32,12 @@ const createGetData = fetch => async (url, opts) => {
const text = await response.text()
const embed = parse(text)

const scripts = embed
.find(el => el.tagName === 'html')
.children.find(el => el.tagName === 'body')
let scripts = embed.find(el => el.tagName === 'html')

if (scripts === undefined) return throwError(ERROR.NOT_SCRIPTS)

scripts = scripts.children
.find(el => el.tagName === 'body')
.children.filter(({ tagName }) => tagName === 'script')

let script = scripts.find(script =>
Expand All @@ -48,9 +62,7 @@ const createGetData = fetch => async (url, opts) => {
return normalizeData({ data })
}

throw new Error(
"Couldn't find any data in embed page that we know how to parse.\nPlease report the problem at https://github.com/microlinkhq/spotify-url-info/issues."
)
return throwError(ERROR.NOT_DATA)
}

function getParsedUrl (url) {
Expand Down
13 changes: 13 additions & 0 deletions test/get-data.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,19 @@ test('getting data for non spotify url string should return rejection', async t
)
})

test('getting data for a deleted spotify url should return rejection', async t => {
const error = await t.throwsAsync(
() => getData('https://open.spotify.com/playlist/7E6aXqOtSnwECFLiCosTmM'),
{
instanceOf: TypeError
}
)
t.is(
error.message,
"Couldn't find scripts to get the data.\nPlease report the problem at https://github.com/microlinkhq/spotify-url-info/issues."
)
})

test('get data for spotify track', async t => {
const url = 'https://open.spotify.com/track/5nTtCOCds6I0PHMNtqelas'
const data = await getData(url)
Expand Down

0 comments on commit a4c8d2f

Please sign in to comment.