implement this.redirect in preload (#83)

This commit is contained in:
Rich Harris
2018-02-17 22:56:47 -05:00
parent f8ea9ebda1
commit bff6f550be
7 changed files with 71 additions and 80 deletions

View File

@@ -34,59 +34,6 @@ export default function create_templates() {
return template.replace(/%sapper\.(\w+)%/g, (match, key) => {
return key in data ? data[key] : '';
});
},
stream: (req: any, res: any, data: Record<string, string | Promise<string>>) => {
let i = 0;
let body = '';
function stream_inner(): Promise<void> {
if (i >= template.length) {
return;
}
const start = template.indexOf('%sapper', i);
if (start === -1) {
const chunk = template.slice(i);
body += chunk;
res.end(chunk);
if (process.send) {
process.send({
__sapper__: true,
url: req.url,
method: req.method,
type: 'text/html',
body
});
}
return;
}
const chunk = template.slice(i, start);
body += chunk;
res.write(chunk);
const end = template.indexOf('%', start + 1);
if (end === -1) {
throw new Error(`Bad template`); // TODO validate ahead of time
}
const tag = template.slice(start + 1, end);
const match = /sapper\.(\w+)/.exec(tag);
if (!match || !(match[1] in data)) throw new Error(`Bad template`); // TODO ditto
return Promise.resolve(data[match[1]]).then(chunk => {
body += chunk;
res.write(chunk);
i = end + 1;
return stream_inner();
});
}
return Promise.resolve().then(stream_inner);
}
};
}