import { Hono } from "npm:hono@3";
import { cors } from "npm:hono/cors";
import { fetch } from "https://esm.town/v/std/fetch";
const app = new Hono();
const YOUR_EMAIL = "jan@phage.directory";
async function unpaywallDOI(doi) {
const url = `https://api.unpaywall.org/v2/${doi}?email=${YOUR_EMAIL}`;
const options = {
method: 'GET',
headers: {
'accept': 'application/json',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36'
}
};
try {
const response = await fetch(url, options);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error('Error:', error);
throw error;
}
}
async function unpaywallSearch(query, additionalParams = {}) {
const url = new URL('https://api.unpaywall.org/v2/search');
url.searchParams.append('query', query);
url.searchParams.append('email', YOUR_EMAIL);
Object.entries(additionalParams).forEach(([key, value]) => {
if (value !== undefined && value !== null) {
url.searchParams.append(key, value);
}
});
const options = {
method: 'GET',
headers: {
'accept': 'application/json',
'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36'
}
};
try {
console.log('search url:', url)
const response = await fetch(url, options);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
return data;
} catch (error) {
console.error('Error:', error);
throw error;
}
}
app.get('/doi/*', async (c) => {
const url = new URL(c.req.url);
const doi = url.pathname.slice(1);
if (!doi) {
return c.json({ error: 'DOI parameter is required' }, 400);
}
try {
console.log({ mode: 'get/unpaywallDOI', doi });
const results = await unpaywallDOI(doi);
return c.json(results);
} catch (error) {
console.error('API error:', error);
return c.json({ error: 'An error occurred while processing your request' }, 500);
}
});
app.get('/search', async (c) => {
const query = c.req.query('query') || c.req.query('q');
const is_oa = c.req.query('is_oa');
const page = c.req.query('page');
if (!query) {
return c.json({ error: 'Query parameter is required' }, 400);
}
try {
console.log({ mode: 'get/unpaywallSearch', query, is_oa, page });
const additionalParams = {};