-
Notifications
You must be signed in to change notification settings - Fork 26
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
refactor: convert ReadMe
into a class
#958
Merged
mjcuva
merged 2 commits into
node/unified-snippet
from
kanad/unified-snippet-class-refactor
Feb 1, 2024
Merged
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -55,160 +55,165 @@ interface ReadMeVersion { | |
version: string; | ||
} | ||
|
||
// See comment at the auth definition below | ||
let readmeAPIKey = ''; | ||
let readmeProjectData: GetProjectResponse200 | undefined; | ||
let readmeVersionData: ReadMeVersion[] | undefined; | ||
|
||
const readme = ( | ||
userFunction: (req: Request, getUser: GetUserFunction) => Promise<GroupingObject | void>, | ||
options: Options = { | ||
disableWebhook: false, | ||
disableMetrics: false, | ||
development: false, | ||
}, | ||
) => { | ||
return async (req: Request, res: Response, next: NextFunction) => { | ||
let requestAPIKey = ''; | ||
let usingManualAPIKey = false; | ||
|
||
const getUser: GetUserFunction = async ({ byAPIKey, byEmail, manualAPIKey }) => { | ||
if (!byAPIKey && !options.disableMetrics) { | ||
console.error( | ||
'Missing required definition for `byAPIKey`. Learn more here: https://docs.readme.com/main/docs/unified-snippet-docs#getuserbyapikey', | ||
); | ||
return next(); | ||
} | ||
if (!byEmail && !options.disableWebhook) { | ||
console.error( | ||
'Missing required definition for `byEmail`. Learn more here: https://docs.readme.com/main/docs/unified-snippet-docs#getuserbyapikey', | ||
); | ||
return next(); | ||
} | ||
/** | ||
* Initialize this class with the API Key for your ReadMe project and use the `express` method | ||
* to return middleware that will send supplied API requests to ReadMe Metrics and configure the ReadMe webhook. | ||
* | ||
* @see {@link https://readme.com/metrics} | ||
* @see {@link https://docs.readme.com/main/docs/unified-snippet-docs} | ||
*/ | ||
export default class ReadMe { | ||
/** | ||
* The API key for your ReadMe project. This ensures your requests end up in | ||
* your dashboard. You can read more about the API key in | ||
* [our docs](https://docs.readme.com/reference/authentication). | ||
*/ | ||
readmeAPIKey: string; | ||
|
||
private readmeProjectData!: GetProjectResponse200; | ||
|
||
private readmeVersionData!: ReadMeVersion[]; | ||
|
||
constructor(key: string) { | ||
this.readmeAPIKey = key; | ||
} | ||
|
||
/** | ||
* Express middleware that will send supplied API requests to ReadMe Metrics and will create a new endpoint for the ReadMe webhook. | ||
*/ | ||
express( | ||
userFunction: (req: Request, getUser: GetUserFunction) => Promise<GroupingObject | void>, | ||
options: Options = { | ||
disableWebhook: false, | ||
disableMetrics: false, | ||
development: false, | ||
}, | ||
) { | ||
return async (req: Request, res: Response, next: NextFunction) => { | ||
let requestAPIKey = ''; | ||
let usingManualAPIKey = false; | ||
|
||
const getUser: GetUserFunction = async ({ byAPIKey, byEmail, manualAPIKey }) => { | ||
if (!byAPIKey && !options.disableMetrics) { | ||
console.error( | ||
'Missing required definition for `byAPIKey`. Learn more here: https://docs.readme.com/main/docs/unified-snippet-docs#getuserbyapikey', | ||
); | ||
return next(); | ||
} | ||
if (!byEmail && !options.disableWebhook) { | ||
console.error( | ||
'Missing required definition for `byEmail`. Learn more here: https://docs.readme.com/main/docs/unified-snippet-docs#getuserbyapikey', | ||
); | ||
return next(); | ||
} | ||
|
||
if (req.path === '/readme-webhook' && req.method === 'POST' && !options.disableWebhook) { | ||
const user = await byEmail(req.body.email); | ||
if (!user) { | ||
throw new Error(`User with email ${req.body.email} not found`); | ||
if (req.path === '/readme-webhook' && req.method === 'POST' && !options.disableWebhook) { | ||
const user = await byEmail(req.body.email); | ||
if (!user) { | ||
throw new Error(`User with email ${req.body.email} not found`); | ||
} | ||
return user; | ||
} | ||
if (manualAPIKey) { | ||
// we should remember this for later | ||
requestAPIKey = manualAPIKey; | ||
usingManualAPIKey = true; | ||
return byAPIKey(manualAPIKey); | ||
} | ||
// Try to figure out where the api key is | ||
try { | ||
requestAPIKey = findAPIKey(req); | ||
} catch (e) { | ||
console.error( | ||
'Could not automatically find an API key in the request. You should pass the API key via `manualAPIKey` in the `getUser` function. Learn more here: https://docs.readme.com/main/docs/unified-snippet-docs#getuserbyapikey', | ||
); | ||
} | ||
return byAPIKey(requestAPIKey); | ||
}; | ||
|
||
const baseUrl = `${req.protocol}://${req.get('host')}${req.baseUrl}`; | ||
|
||
if (!this.readmeProjectData) { | ||
readmeSdk.auth(this.readmeAPIKey); | ||
try { | ||
this.readmeProjectData = (await readmeSdk.getProject()).data; | ||
this.readmeVersionData = (await readmeSdk.getVersions()).data as ReadMeVersion[]; | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
} catch (e: any) { | ||
// TODO: Maybe send this to sentry? | ||
if (e.status === 401) { | ||
console.error('Invalid ReadMe API key. Contact [email protected] for help!'); | ||
console.error(e.data); | ||
} else { | ||
console.error('Error calling ReadMe API. Contact [email protected] for help!'); | ||
console.error(e.data); | ||
} | ||
// Don't want to cause an error in their API | ||
return next(); | ||
} | ||
return user; | ||
} | ||
if (manualAPIKey) { | ||
// we should remember this for later | ||
requestAPIKey = manualAPIKey; | ||
usingManualAPIKey = true; | ||
return byAPIKey(manualAPIKey); | ||
} | ||
// Try to figure out where the api key is | ||
try { | ||
requestAPIKey = findAPIKey(req); | ||
} catch (e) { | ||
console.error( | ||
'Could not automatically find an API key in the request. You should pass the API key via `manualAPIKey` in the `getUser` function. Learn more here: https://docs.readme.com/main/docs/unified-snippet-docs#getuserbyapikey', | ||
); | ||
} | ||
return byAPIKey(requestAPIKey); | ||
}; | ||
|
||
const baseUrl = `${req.protocol}://${req.get('host')}${req.baseUrl}`; | ||
|
||
if (!readmeProjectData) { | ||
readmeSdk.auth(readmeAPIKey); | ||
try { | ||
readmeProjectData = (await readmeSdk.getProject()).data; | ||
readmeVersionData = (await readmeSdk.getVersions()).data as ReadMeVersion[]; | ||
// eslint-disable-next-line @typescript-eslint/no-explicit-any | ||
} catch (e: any) { | ||
// TODO: Maybe send this to sentry? | ||
if (e.status === 401) { | ||
console.error('Invalid ReadMe API key. Contact [email protected] for help!'); | ||
console.error(e.data); | ||
} else { | ||
console.error('Error calling ReadMe API. Contact [email protected] for help!'); | ||
console.error(e.data); | ||
if (req.path === '/readme-webhook' && req.method === 'POST' && !options.disableWebhook) { | ||
try { | ||
verifyWebhook( | ||
req.body, | ||
req.headers['readme-signature'] as string, | ||
this.readmeProjectData.jwtSecret as string, | ||
); | ||
const user = await userFunction(req, getUser); | ||
return res.send(user); | ||
} catch (e) { | ||
return res.status(400).json({ error: (e as Error).message }); | ||
} | ||
} else if (req.path === '/readme-setup' && options.development) { | ||
const setupHtml = buildSetupView({ | ||
baseUrl, | ||
subdomain: this.readmeProjectData.subdomain as string, | ||
stableVersion: this.readmeVersionData?.find(version => version.is_stable)?.version || '1.0', | ||
readmeAPIKey: this.readmeAPIKey, | ||
disableMetrics: options.disableMetrics, | ||
disableWebhook: options.disableWebhook, | ||
}); | ||
return res.send(setupHtml); | ||
} else if (req.path === '/webhook-test' && options.development) { | ||
const email = req.query.email as string; | ||
try { | ||
const webhookData = await testVerifyWebhook(baseUrl, email, this.readmeProjectData.jwtSecret as string); | ||
return res.json({ ...webhookData }); | ||
} catch (e) { | ||
return res.status(400).json({ error: (e as Error).message }); | ||
} | ||
// Don't want to cause an error in their API | ||
return next(); | ||
} | ||
} | ||
|
||
if (req.path === '/readme-webhook' && req.method === 'POST' && !options.disableWebhook) { | ||
try { | ||
verifyWebhook(req.body, req.headers['readme-signature'] as string, readmeProjectData.jwtSecret as string); | ||
const user = await userFunction(req, getUser); | ||
return res.send(user); | ||
} catch (e) { | ||
return res.status(400).json({ error: (e as Error).message }); | ||
} | ||
} else if (req.path === '/readme-setup' && options.development) { | ||
const setupHtml = buildSetupView({ | ||
baseUrl, | ||
subdomain: readmeProjectData.subdomain as string, | ||
stableVersion: readmeVersionData?.find(version => version.is_stable)?.version || '1.0', | ||
readmeAPIKey, | ||
disableMetrics: options.disableMetrics, | ||
disableWebhook: options.disableWebhook, | ||
}); | ||
return res.send(setupHtml); | ||
} else if (req.path === '/webhook-test' && options.development) { | ||
const email = req.query.email as string; | ||
try { | ||
const webhookData = await testVerifyWebhook(baseUrl, email, readmeProjectData.jwtSecret as string); | ||
return res.json({ ...webhookData }); | ||
} catch (e) { | ||
return res.status(400).json({ error: (e as Error).message }); | ||
} | ||
} | ||
|
||
try { | ||
const user = await userFunction(req, getUser); | ||
if (!user || !Object.keys(user).length || options.disableMetrics) return next(); | ||
|
||
const groupId = getGroupIdByApiKey(user, requestAPIKey); | ||
if (!groupId) { | ||
console.error( | ||
usingManualAPIKey | ||
? 'The API key you passed in via `manualAPIKey` could not be found in the user object you provided.' | ||
: 'Could not automatically find an API key in the request. You should pass the API key via `manualAPIKey` in the `getUser` function. Learn more here: https://docs.readme.com/main/docs/unified-snippet-docs#/getuserbyapikey', | ||
if (!user || !Object.keys(user).length || options.disableMetrics) return next(); | ||
|
||
const groupId = getGroupIdByApiKey(user, requestAPIKey); | ||
if (!groupId) { | ||
console.error( | ||
usingManualAPIKey | ||
? 'The API key you passed in via `manualAPIKey` could not be found in the user object you provided.' | ||
: 'Could not automatically find an API key in the request. You should pass the API key via `manualAPIKey` in the `getUser` function. Learn more here: https://docs.readme.com/main/docs/unified-snippet-docs#/getuserbyapikey', | ||
); | ||
return next(); | ||
} | ||
|
||
log( | ||
this.readmeAPIKey, | ||
req, | ||
res, | ||
{ | ||
apiKey: groupId, | ||
label: user.label ? user.label : user.name, | ||
email: user.email, | ||
}, | ||
options, | ||
); | ||
} catch (e) { | ||
return next(); | ||
} | ||
|
||
log( | ||
readmeAPIKey, | ||
req, | ||
res, | ||
{ | ||
apiKey: groupId, | ||
label: user.label ? user.label : user.name, | ||
email: user.email, | ||
}, | ||
options, | ||
); | ||
} catch (e) { | ||
return next(); | ||
} | ||
return next(); | ||
}; | ||
}; | ||
|
||
/** | ||
* This method configures the API Key for your ReadMe project and returns middleware that will | ||
* send supplied API requests to ReadMe Metrics and configure the ReadMe webhook. | ||
* | ||
* @see {@link https://readme.com/metrics} | ||
* @see {@link https://docs.readme.com/main/docs/unified-snippet-docs} | ||
* @param key The API key for your ReadMe project. This ensures your requests end up in | ||
* your dashboard. You can read more about the API key in | ||
* [our docs](https://docs.readme.com/reference/authentication). | ||
*/ | ||
function ReadMe(key: string) { | ||
readmeAPIKey = key; | ||
// Reset the cache for the ReadMe project if the api key changes | ||
readmeProjectData = undefined; | ||
return { | ||
express: readme, // Only works with Express for now | ||
}; | ||
}; | ||
} | ||
} | ||
|
||
export default ReadMe; |
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
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -238,7 +238,7 @@ describe('#metrics', function () { | |
], | ||
); | ||
|
||
const readme = readmeio.ReadMe(apiKey); | ||
const readme = new readmeio.ReadMe(apiKey); | ||
app = express(); | ||
app.use( | ||
readme.express((req, getUser) => { | ||
|
@@ -249,22 +249,22 @@ describe('#metrics', function () { | |
return undefined; | ||
} | ||
|
||
return { | ||
return Promise.resolve({ | ||
keys: [{ apiKey: requestApiKey, name: 'test' }], | ||
name: 'test', | ||
email: '[email protected]', | ||
}; | ||
}); | ||
}, | ||
byEmail: (email: string) => { | ||
if (!email) { | ||
return undefined; | ||
} | ||
|
||
return { | ||
return Promise.resolve({ | ||
keys: [{ apiKey: endUserApiKey, name: 'test' }], | ||
name: 'test', | ||
email: '[email protected]', | ||
}; | ||
}); | ||
}, | ||
}); | ||
}), | ||
|
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
moving everything into a class will also contain this data to the specific instance. as-is it'd be difficult/impossible to spin up different instances of the SDK against different projects (like a group of microservices) because this data would get clobbered between each