feat: save new gists to database

pull/2572/head
Luke Edwards 7 years ago
parent 5298f8ea35
commit f672e6a721

@ -0,0 +1,24 @@
exports.up = DB => {
DB.sql(`
create table if not exists gists (
id serial primary key,
uid uuid NOT NULL DEFAULT gen_random_uuid(),
user_id integer REFERENCES users(id) not null,
name character varying(255) not null,
files json not null,
created_at timestamp with time zone NOT NULL DEFAULT now(),
updated_at timestamp with time zone
);
create unique index if not exists gists_pkey ON gists(id int4_ops);
create index if not exists gists_user_id_key ON gists(user_id int4_ops);
`);
};
exports.down = DB => {
DB.sql(`
drop table if exists gists cascade;
drop index if exists gists_user_id_key;
drop index if exists gists_pkey;
`);
};

@ -15,7 +15,6 @@
"testsrc": "mocha -r esm test/**" "testsrc": "mocha -r esm test/**"
}, },
"dependencies": { "dependencies": {
"@polka/parse": "^1.0.0-next.1",
"@polka/send": "^1.0.0-next.2", "@polka/send": "^1.0.0-next.2",
"devalue": "^1.1.0", "devalue": "^1.1.0",
"do-not-zip": "^1.0.0", "do-not-zip": "^1.0.0",

@ -2,7 +2,6 @@ import polka from 'polka';
import devalue from 'devalue'; import devalue from 'devalue';
import send from '@polka/send'; import send from '@polka/send';
import { get, post } from 'httpie'; import { get, post } from 'httpie';
import { json } from '@polka/parse';
import { parse, stringify } from 'querystring'; import { parse, stringify } from 'querystring';
import { decode, sign, verify } from './token'; import { decode, sign, verify } from './token';
import { find, query } from '../utils/db'; import { find, query } from '../utils/db';
@ -65,7 +64,7 @@ export function toUser(obj={}) {
} }
export function API() { export function API() {
const app = polka({ onError }).use(json()); const app = polka({ onError });
if (GITHUB_CLIENT_ID) { if (GITHUB_CLIENT_ID) {
app.get('/auth/login', (req, res) => { app.get('/auth/login', (req, res) => {

@ -1,55 +1,30 @@
import fetch from 'node-fetch';
import { body } from './_utils.js';
import send from '@polka/send'; import send from '@polka/send';
import { query } from '../../utils/db';
import { isUser } from '../../backend/auth';
import { body } from './_utils.js';
export async function post(req, res) { export async function post(req, res) {
const user = req.session.passport && req.session.passport.user; const user = await isUser(req, res);
if (!user) return; // response already sent
if (!user) {
return send(res, 403, { error: 'unauthorized' });
}
try { try {
const { name, components } = await body(req); const { name, components } = await body(req);
const files = { const files = {};
'meta.json': {
content: JSON.stringify({
svelte: true
}, null, ' ')
},
'README.md': {
content: `Created with [svelte.dev/repl](https://svelte.dev/repl)`
}
};
components.forEach(component => { components.forEach(component => {
const file = `${component.name}.${component.type}`; const text = component.source.trim();
if (!component.source.trim()) { if (!text.length) return; // skip empty file
throw new Error(`GitHub does not allow saving gists with empty files - ${file}`); files[`${component.name}.${component.type}`] = text;
}
files[file] = { content: component.source };
});
const r = await fetch(`https://api.github.com/gists`, {
method: 'POST',
headers: {
Authorization: `token ${user.token}`
},
body: JSON.stringify({
description: name,
files,
public: false
})
}); });
const gist = await r.json(); const [row] = await query(`
insert into gists(user_id, name, files)
values ($1, $2, $3) returning *`, [user.id, name, files]);
send(res, r.status, { send(res, 201, {
id: gist.id, uid: row.uid,
description: gist.description, name: row.name,
owner: gist.owner, files: row.files,
html_url: gist.html_url,
files: gist.files
}); });
} catch (err) { } catch (err) {
send(res, 500, { send(res, 500, {

@ -26,7 +26,7 @@
return new Promise(f => setTimeout(f, ms)); return new Promise(f => setTimeout(f, ms));
} }
let canSave; $: Authorization = $user && `Bearer ${$user.token}`;
$: canSave = !!$user && !!gist && !!gist.owner && $user.id == gist.owner.id; // comparing number and string $: canSave = !!$user && !!gist && !!gist.owner && $user.id == gist.owner.id; // comparing number and string
function handleKeydown(event) { function handleKeydown(event) {
@ -57,7 +57,7 @@
try { try {
const r = await fetch(`gist/create`, { const r = await fetch(`gist/create`, {
method: 'POST', method: 'POST',
credentials: 'include', headers: { Authorization },
body: JSON.stringify({ body: JSON.stringify({
name, name,
components components

Loading…
Cancel
Save