Skip to content
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
merged 2 commits into from
Feb 1, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
291 changes: 148 additions & 143 deletions packages/node/src/lib/ReadMe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Comment on lines -58 to -61
Copy link
Member

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


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;
10 changes: 5 additions & 5 deletions packages/node/test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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) => {
Expand All @@ -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]',
};
});
},
});
}),
Expand Down
Loading