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

fix: QA changes #40

Merged
merged 31 commits into from
Aug 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
7a10eb6
debug: req
loks0n Aug 4, 2023
4d48e46
fix: origin issues
loks0n Aug 4, 2023
a6d9db9
fix: referer bugs
loks0n Aug 4, 2023
4524d25
chore: improve comment
loks0n Aug 4, 2023
f62b808
debug: improve logging
loks0n Aug 4, 2023
7685ea6
fix: ruby env vars
loks0n Aug 7, 2023
7f83cf9
chore: fmt, add missing import
loks0n Aug 11, 2023
cfb92a4
fix: comment bug
loks0n Aug 15, 2023
4f7e95b
fix: response
loks0n Aug 15, 2023
6a5c2e9
debug: obj response bug
loks0n Aug 15, 2023
9fffd95
fix: response accessor
loks0n Aug 15, 2023
28bbe10
feat: standardise message on pages
loks0n Aug 15, 2023
eaec3b7
feat: use meilisearch api
loks0n Aug 15, 2023
3ce6332
fix: text
loks0n Aug 15, 2023
5d7aef7
debug: output task data
loks0n Aug 15, 2023
d07326d
fix: set document id
loks0n Aug 16, 2023
8a37da8
fix: set primary key
loks0n Aug 16, 2023
563024d
chore: improve title
loks0n Aug 16, 2023
9697537
fix: onSearch not defined
loks0n Aug 16, 2023
dc82fa8
fix: dont use esm
loks0n Aug 16, 2023
f2a025d
fix: return hits from onSearch
loks0n Aug 16, 2023
e333817
fix: display hits
loks0n Aug 16, 2023
a258b5b
fix: output hits
loks0n Aug 16, 2023
a7153f3
chore: standardise sync templates
loks0n Aug 16, 2023
a4c3393
feat: robust setup
loks0n Aug 17, 2023
9887015
fix: qa issues
loks0n Aug 17, 2023
fee9343
chore: update env var names
loks0n Aug 17, 2023
70e0eee
fix: env vars
loks0n Aug 17, 2023
894c44a
fix: remove unnecessary await
loks0n Aug 17, 2023
422bacc
fix: remove redundant type
loks0n Aug 17, 2023
cb3740f
chore: use try catch over if
loks0n Aug 18, 2023
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
5 changes: 2 additions & 3 deletions node/analyze-with-perspectiveapi/static/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,8 @@ <h1 class="heading-level-1">Analyze with Perspective API Demo</h1>
class="body-text-1 u-normal u-margin-block-start-8"
style="max-width: 50rem"
>
Use this page to test your implementation with PerspectiveAPI. Use
the input below to enter text and receive the toxicity measure of
the text as a response.
Use this page to test your implementation with PerspectiveAPI. Enter
text and receive the toxicity measure of the text as a response.
</p>
</div>
</div>
Expand Down
5 changes: 2 additions & 3 deletions node/censor-with-redact/static/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,8 @@ <h1 class="heading-level-1">Censor with Redact API Demo</h1>
class="body-text-1 u-normal u-margin-block-start-8"
style="max-width: 50rem"
>
Use this page to test your implementation with Redact API. Use the
input below to enter text and receive the censored message as a
response.
Use this page to test your implementation with Redact API. Enter
text and receive the censored message as a response.
</p>
</div>
</div>
Expand Down
16 changes: 8 additions & 8 deletions node/discord-command-bot/src/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,14 @@ export default async ({ req, res, error, log }) => {
'DISCORD_TOKEN',
]);

const verified = await verifyKey(
req.bodyRaw,
req.headers['x-signature-ed25519'],
req.headers['x-signature-timestamp'],
process.env.DISCORD_PUBLIC_KEY
);

if (!verified) {
if (
!verifyKey(
req.bodyRaw,
req.headers['x-signature-ed25519'],
req.headers['x-signature-timestamp'],
process.env.DISCORD_PUBLIC_KEY
)
) {
error('Invalid request.');
return res.json({ error: 'Invalid request signature' }, 401);
}
Expand Down
7 changes: 6 additions & 1 deletion node/email-contact-form/src/cors.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
export function isOriginPermitted(req) {
if (!process.env.ALLOWED_ORIGINS || process.env.ALLOWED_ORIGINS === '*')
if (
!process.env.ALLOWED_ORIGINS ||
process.env.ALLOWED_ORIGINS === '*' ||
!req.headers['origin']
)
return true;
const allowedOriginsArray = process.env.ALLOWED_ORIGINS.split(',');
return allowedOriginsArray.includes(req.headers['origin']);
}

export function getCorsHeaders(req) {
if (!req.headers['origin']) return {};
return {
'Access-Control-Allow-Origin':
!process.env.ALLOWED_ORIGINS || process.env.ALLOWED_ORIGINS === '*'
Expand Down
18 changes: 10 additions & 8 deletions node/email-contact-form/src/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,16 +34,14 @@ export default async ({ req, res, log, error }) => {
});
}

throwIfMissing(req.headers, ['referer', 'origin']);

if (req.headers['content-type'] !== 'application/x-www-form-urlencoded') {
error('Incorrect content type.');
return res.redirect(
urlWithCodeParam(req.headers['referer'], ErrorCode.INVALID_REQUEST)
);
}

if (!isOriginPermitted(req.headers['origin'])) {
if (!isOriginPermitted(req)) {
error('Origin not permitted.');
return res.redirect(
urlWithCodeParam(req.headers['referer'], ErrorCode.INVALID_REQUEST)
Expand All @@ -57,23 +55,23 @@ export default async ({ req, res, log, error }) => {
return res.redirect(
urlWithCodeParam(req.headers['referer'], err.message),
301,
getCorsHeaders(req.headers['origin'])
getCorsHeaders(req)
);
}

try {
sendEmail({
to: process.env.SUBMIT_EMAIL,
from: /** @type {string} */ (form['email']),
subject: `New form submission: ${origin}`,
subject: `New form submission: ${req.headers['referer']}`,
text: templateFormMessage(form),
});
} catch (err) {
error(err.message);
return res.redirect(
urlWithCodeParam(req.headers['referer'], ErrorCode.SERVER_ERROR),
301,
getCorsHeaders(req.headers['origin'])
getCorsHeaders(req)
);
}

Expand All @@ -83,9 +81,13 @@ export default async ({ req, res, log, error }) => {
});
}

const baseUrl = new URL(req.headers['referer']).origin;

log(`Redirecting to ${new URL(form._next, baseUrl).toString()}`);

return res.redirect(
new URL(form._next, req.headers['origin']).toString(),
new URL(form._next, baseUrl).toString(),
301,
getCorsHeaders(req.headers['origin'])
getCorsHeaders(req)
);
};
13 changes: 5 additions & 8 deletions node/email-contact-form/src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,10 @@ export function getStaticFile(fileName) {
*/
export function templateFormMessage(form) {
return `You've received a new message.\n
${Object.entries(form)
.filter(([key]) => key !== '_next')
.map(([key, value]) => `${key}: ${value}`)
.join('\n')}`;
${Object.entries(form)
.filter(([key]) => key !== '_next')
.map(([key, value]) => `${key}: ${value}`)
.join('\n')}`;
}

/**
Expand All @@ -57,13 +57,10 @@ export function urlWithCodeParam(baseUrl, codeParam) {
return url.toString();
}

/**
* @param {import('nodemailer').SendMailOptions} options
*/
export async function sendEmail(options) {
const transport = nodemailer.createTransport({
// @ts-ignore
// Not sure what's going on here.
// Bypass some weird type checks
host: process.env.SMTP_HOST,
port: process.env.SMTP_PORT || 587,
auth: {
Expand Down
1 change: 0 additions & 1 deletion node/email-contact-form/static/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,6 @@ <h1 class="heading-level-1">Contact</h1>
placeholder="Your Message"
required
></textarea>
<input type="hidden" name="_next" value="/success" />
<button class="button" type="submit">Submit</button>
</form>
</div>
Expand Down
32 changes: 16 additions & 16 deletions node/generate-pdf/src/faker.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
import { faker } from '@faker-js/faker';

export function generateFakeOrder() {
const items = Array.from(
{ length: faker.number.int({ min: 1, max: 5 }) },
() => ({
description: faker.commerce.productName(),
quantity: faker.number.int({ min: 1, max: 10 }),
cost: faker.commerce.price(),
})
);
const items = Array.from(
{ length: faker.number.int({ min: 1, max: 5 }) },
() => ({
description: faker.commerce.productName(),
quantity: faker.number.int({ min: 1, max: 10 }),
cost: faker.commerce.price(),
})
);

return {
id: faker.string.uuid(),
date: faker.date.past(),
name: faker.person.fullName(),
items,
total: items.reduce((acc, { cost }) => acc + parseFloat(cost), 0),
};
}
return {
id: faker.string.uuid(),
date: faker.date.past(),
name: faker.person.fullName(),
items,
total: items.reduce((acc, { cost }) => acc + parseFloat(cost), 0),
};
}
73 changes: 37 additions & 36 deletions node/generate-pdf/src/pdf.js
Original file line number Diff line number Diff line change
@@ -1,40 +1,41 @@
import { PDFDocument } from 'pdf-lib';
import { Buffer } from 'node:buffer';

export async function createPdf({ id, date, name, items, total }) {
const document = await PDFDocument.create();
const page = document.addPage([595.28, 841.89]); // A4 size

page.drawText('Sample Invoice', { x: 50, y: 750, size: 20 });
page.drawText(new Date(date).toLocaleDateString(), {
x: 400,
y: 750,
size: 15,
});

page.drawText(`Hello, ${name}!`, {
x: 50,
y: 700,
size: 30,
});

page.drawText(`Order ID: ${id}`, {
x: 50,
y: 650,
size: 10,
});

page.drawText(`Total: $${total}`, { x: 50, y: 600, size: 15 });

const orderList = items
.map(
({ description, quantity, cost }) =>
`${description} x ${quantity} = $${cost}`
)
.join('\n');

page.drawText(orderList, { x: 50, y: 550, size: 15 });

const pdfBytes = await document.save();

return Buffer.from(pdfBytes.buffer);
const document = await PDFDocument.create();
const page = document.addPage([595.28, 841.89]); // A4 size

page.drawText('Sample Invoice', { x: 50, y: 750, size: 20 });
page.drawText(new Date(date).toLocaleDateString(), {
x: 400,
y: 750,
size: 15,
});

page.drawText(`Hello, ${name}!`, {
x: 50,
y: 700,
size: 30,
});

page.drawText(`Order ID: ${id}`, {
x: 50,
y: 650,
size: 10,
});

page.drawText(`Total: $${total}`, { x: 50, y: 600, size: 15 });

const orderList = items
.map(
({ description, quantity, cost }) =>
`${description} x ${quantity} = $${cost}`
)
.join('\n');

page.drawText(orderList, { x: 50, y: 550, size: 15 });

const pdfBytes = await document.save();

return Buffer.from(pdfBytes);
}
6 changes: 3 additions & 3 deletions node/github-issue-bot/src/github.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,10 @@ class GithubService {
* @param {any} issue
* @param {string} comment
*/
async postComment(issue, comment) {
async postComment(repository, issue, comment) {
await this.octokit.issues.createComment({
owner: issue.repository.owner.login,
repo: issue.repository.name,
owner: repository.owner.login,
repo: repository.name,
issue_number: issue.number,
body: comment,
});
Expand Down
10 changes: 7 additions & 3 deletions node/github-issue-bot/src/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,16 @@ export default async ({ res, req, log, error }) => {
return res.json({ ok: false, error: 'Invalid signature' }, 401);
}

if (!github.isIssueOpenedEvent(req)) {
log('Received non-issue event - ignoring');
return res.json({ ok: true });
}

await github.postComment(
req.body.repository,
req.body.issue,
`Thanks for the issue report @${req.body.issue.user.login}! We will look into it as soon as possible.`
);

if (!github.isIssueOpenedEvent(req)) {
return res.json({ ok: true });
}
return res.json({ ok: true });
};
21 changes: 10 additions & 11 deletions node/prompt-chatgpt/src/main.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { OpenAIApi, Configuration } from 'openai';
import { getStaticFile, throwIfMissing } from './utils.js';

export default async ({ req, res, error }) => {
export default async ({ req, res }) => {
throwIfMissing(process.env, ['OPENAI_API_KEY']);

if (req.method === 'GET') {
Expand All @@ -22,16 +22,15 @@ export default async ({ req, res, error }) => {
})
);

const response = await openai.createChatCompletion({
model: 'gpt-3.5-turbo',
max_tokens: parseInt(process.env.OPENAI_MAX_TOKENS ?? '512'),
messages: [{ role: 'user', content: req.body.prompt }],
});

const completion = response.data?.choices[0]?.message ?? '';
if (!completion) {
try {
const response = await openai.createChatCompletion({
model: 'gpt-3.5-turbo',
max_tokens: parseInt(process.env.OPENAI_MAX_TOKENS ?? '512'),
messages: [{ role: 'user', content: req.body.prompt }],
});
const completion = response.data.choices[0].message?.content;
return res.json({ ok: true, completion }, 200);
} catch (err) {
return res.json({ ok: false, error: 'Failed to query model.' }, 500);
}

return res.json({ ok: true, completion }, 200);
};
5 changes: 2 additions & 3 deletions node/prompt-chatgpt/static/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,8 @@ <h1 class="heading-level-1">Prompt ChatGPT Demo</h1>
class="body-text-1 u-normal u-margin-block-start-8"
style="max-width: 50rem"
>
This is demo application. You can ue this app to ensure
implementation with ChatGPT works properly. Use input below to
enter prompts and get a response.
Use this page to test your implementation with OpenAI ChatGPT. Enter
text and receive the model output as a response.
</p>
</div>
</div>
Expand Down
1 change: 1 addition & 0 deletions node/sync-with-algolia/env.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ declare global {
interface ProcessEnv {
ALGOLIA_APP_ID: string;
ALGOLIA_ADMIN_API_KEY: string;
ALGOLIA_SEARCH_API_KEY: string;
ALGOLIA_INDEX_ID: string;
APPWRITE_ENDPOINT?: string;
APPWRITE_API_KEY: string;
Expand Down
Loading