Last active
November 3, 2024 22:35
-
-
Save humphd/74cf88283239c62f53caff5cddf4cfe5 to your computer and use it in GitHub Desktop.
Convert a DOI or DOI URL to JSON via CrossRef API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Gets JSON citation data from the CrossRef API for a DOI or DOI URL | |
* @param doiOrUrl A DOI or DOI URL | |
*/ | |
export async function doi2json(doiOrUrl: string) { | |
// Extract the DOI from the URL or use it directly if it's not a URL | |
const doi = doiOrUrl.replace(/^https?:\/\/doi\.org\//, ''); | |
// Fetch data from the CrossRef API | |
const response = await fetch(`https://api.crossref.org/works/${doi}`); | |
if (!response.ok) { | |
throw new Error(`HTTP error! status: ${response.status}`); | |
} | |
const { message } = await response.json(); | |
// Strip out the references, which are huge and not needed | |
const { reference, ...info } = message; | |
// If there are more than 20 authors, help the LLM pull the list apart | |
if (info.author.length > 20) { | |
const modifiedAuthors = info.author.map((author, idx) => { | |
const isRequiredInCitation = idx === info.author.length - 1 || idx < 20; | |
return { | |
// Let the LLM know which author this is in the set of authors | |
authorNumber: idx + 1, | |
// Give a clue about the need to include/exclude this author | |
isAuthorRequiredInCitation, | |
...author | |
}; | |
}); | |
return { | |
...info, | |
// Count the authors for the LLM | |
authorCount: info.author.length, | |
// Provide additional instuctions hint about how to do the authors list in this case | |
apaCitationInstructions: "Remember to include ALL of the first 19 authors along with the final author", | |
author: modifiedAuthors | |
}; | |
} | |
return { | |
authorCount: info.author.length, | |
...info, | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment