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

feat: ssr #725

Merged
merged 32 commits into from
Jan 19, 2024
Merged
Show file tree
Hide file tree
Changes from 23 commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
6708779
feat: setSession helper for web
loks0n Oct 11, 2023
1c1d3f9
feat: simpler setSession
loks0n Nov 22, 2023
db438b2
feat: set templates
loks0n Dec 5, 2023
838799f
chore: revert set session
loks0n Dec 12, 2023
e6e7634
feat: use unidici over axios
loks0n Dec 12, 2023
4431e1a
feat: replace form-data
loks0n Dec 13, 2023
57c684b
feat: use undici for cli
loks0n Dec 13, 2023
deeb053
Merge branch 'master' of https://github.com/appwrite/sdk-generator in…
loks0n Dec 13, 2023
503ce5d
chore: use earlier undici
loks0n Dec 13, 2023
1488884
fix: deno fromBlob
loks0n Dec 13, 2023
bae06f8
feat: depr node 12, add node 18
loks0n Dec 13, 2023
f417e13
fix: node
loks0n Dec 13, 2023
935312e
fix: headers
loks0n Dec 13, 2023
51de214
fix: flattenParams
loks0n Dec 13, 2023
38017fe
fix: flatten bugs
loks0n Dec 13, 2023
6fd8406
fix: path building
loks0n Dec 14, 2023
3a00795
feat: node chunked uploads with undici
loks0n Dec 14, 2023
1f82372
fix: missing import
loks0n Dec 14, 2023
6b7098d
test: replace cli node 14 with node 18
loks0n Dec 14, 2023
13ec5ec
chore: revert cli changes
loks0n Dec 14, 2023
0b367db
chore: revert cli change
loks0n Dec 14, 2023
ffcd357
test: enable node 20 disable 14
loks0n Dec 14, 2023
db88d1f
chore: rename class
loks0n Dec 14, 2023
713ebdf
Merge branch '1.5.x' of https://github.com/appwrite/sdk-generator int…
loks0n Dec 18, 2023
30faacb
chore: condense throws
loks0n Dec 18, 2023
e2e7dd2
fix: tests
loks0n Dec 18, 2023
daa78dc
Merge branch '1.5.x' of https://github.com/appwrite/sdk-generator int…
loks0n Dec 24, 2023
5a33054
chore: remove 'arraybuffer' param
loks0n Dec 26, 2023
67a67dc
Revert "chore: remove 'arraybuffer' param"
loks0n Dec 26, 2023
5a3a672
fix: arraybuffer responses
loks0n Dec 26, 2023
379ff46
feat: docstrings for InputFile class
loks0n Dec 26, 2023
b9340ed
fix: inputFile types
loks0n Dec 26, 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
2 changes: 1 addition & 1 deletion .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ jobs:
fail-fast: false
matrix:
php-version: ['8.1']
sdk: [Android11Java8, Android11Java11, Android12Java8, Android12Java11, CLINode14, CLINode16, DartBeta, DartStable, Deno1193, Deno1303, DotNet60, DotNet70, FlutterStable, FlutterBeta, Go112, Go118, KotlinJava8, KotlinJava11, KotlinJava17, Node12, Node14, Node16, PHP74, PHP80, Python38, Python39, Python310, Ruby27, Ruby30, Ruby31, AppleSwift55, Swift55, WebChromium, WebNode]
sdk: [Android11Java8, Android11Java11, Android12Java8, Android12Java11, CLINode14, CLINode16, DartBeta, DartStable, Deno1193, Deno1303, DotNet60, DotNet70, FlutterStable, FlutterBeta, Go112, Go118, KotlinJava8, KotlinJava11, KotlinJava17, Node16, Node18, Node20, PHP74, PHP80, Python38, Python39, Python310, Ruby27, Ruby30, Ruby31, AppleSwift55, Swift55, WebChromium, WebNode]

steps:
- name: Checkout repository
Expand Down
79 changes: 40 additions & 39 deletions templates/deno/src/client.ts.twig
Original file line number Diff line number Diff line change
Expand Up @@ -61,78 +61,79 @@ export class Client {
return this;
}

withoutHeader(key: string, headers: Payload): Payload {
return Object.keys(headers).reduce((acc: Payload, cv: string) => {
if (cv === 'content-type') return acc;
acc[cv] = headers[cv];
return acc;
}, {})
}
async call(method: string, path: string = "", headers: Payload = {}, params: Payload = {}) {
headers = {...this.headers, ...headers};
const url = new URL(this.endpoint + path);

async call(method: string, path: string = '', headers: Payload = {}, params: Payload = {}) {
headers = Object.assign({}, this.headers, headers);
let body: string | FormData | undefined = undefined;

let body;
const url = new URL(this.endpoint + path);
if (method.toUpperCase() === 'GET') {
url.search = new URLSearchParams(this.flatten(params)).toString();
body = null;
} else if (headers['content-type'].toLowerCase().startsWith('multipart/form-data')) {
headers = this.withoutHeader('content-type', headers);
if (method.toUpperCase() === "GET") {
url.search = new URLSearchParams(Client.flatten(params)).toString();
} else if (headers["content-type"]?.toLowerCase().startsWith("multipart/form-data")) {
delete headers["content-type"];
const formData = new FormData();
const flatParams = this.flatten(params);
for (const key in flatParams) {
const value = flatParams[key];

if(value && value.type && value.type === 'file') {
const flatParams = Client.flatten(params);

for (const [key, value] of Object.entries(flatParams)) {
if (value && value.type && value.type === "file") {
formData.append(key, value.file, value.filename);
} else {
formData.append(key, flatParams[key]);
formData.append(key, value);
}
}

body = formData;
} else {
body = JSON.stringify(params);
}

const options = {
method: method.toUpperCase(),
headers: headers,
body: body,
};

try {
let response = await fetch(url.toString(), options);
const contentType = response.headers.get('content-type');

if (contentType && contentType.includes('application/json')) {
const response = await fetch(url.toString(), {
method,
headers,
body,
});
const contentType = response.headers.get("content-type");

if (contentType && contentType.includes("application/json")) {
if (response.status >= 400) {
let res = await response.json();
throw new {{ spec.title | caseUcfirst}}Exception(res.message, res.status, res.type ?? "", res);
const json = await response.json();
throw new {{ spec.title | caseUcfirst}}Exception(
json.message,
json.status,
json.type ?? "",
json
);
}

return response.json();
} else {
if (response.status >= 400) {
let res = await response.text();
throw new {{ spec.title | caseUcfirst}}Exception(res, response.status, "", null);
const text = await response.text();
throw new {{ spec.title | caseUcfirst}}Exception(text, response.status, "", null);
}
return response;
}
} catch(error) {
throw new {{ spec.title | caseUcfirst}}Exception(error?.response?.message || error.message, error?.response?.code, error?.response?.type, error.response);
} catch (error) {
throw new {{ spec.title | caseUcfirst}}Exception(
error?.response?.message || error.message,
error?.response?.code,
error?.response?.type,
error.response
);
}
}

flatten(data: Payload, prefix = '') {
static flatten(data: Payload, prefix = '') {
let output: Payload = {};

for (const key in data) {
let value = data[key];
let finalKey = prefix ? prefix + '[' + key +']' : key;

if (Array.isArray(value)) {
output = { ...output, ...this.flatten(value, finalKey) }; // @todo: handle name collision here if needed
output = { ...output, ...Client.flatten(value, finalKey) }; // @todo: handle name collision here if needed
}
else {
output[finalKey] = value;
Expand Down
6 changes: 6 additions & 0 deletions templates/deno/src/inputFile.ts.twig
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,12 @@ export class InputFile {
return new InputFile(stream, filename, size);
};

static fromBlob = async (blob: Blob, filename: string) => {
const arrayBuffer = await blob.arrayBuffer();
const buffer = new Uint8Array(arrayBuffer);
return InputFile.fromBuffer(buffer, filename);
};

static fromBuffer = (buffer: Uint8Array, filename: string): InputFile => {
const stream = _bufferToString(buffer);
const size = buffer.byteLength;
Expand Down
125 changes: 43 additions & 82 deletions templates/node/base/requests/file.twig
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
{% for parameter in method.parameters.all %}
{% if parameter.type == 'file' %}
const size = {{ parameter.name | caseCamel | escapeKeyword }}.size;

const size = {{ parameter.name | caseCamel | escapeKeyword }}.size;

const apiHeaders = {
{% for parameter in method.parameters.header %}
'{{ parameter.name }}': ${{ parameter.name | caseCamel | escapeKeyword }},
Expand All @@ -28,117 +29,77 @@
{% endif %}
{% endfor %}

let currentChunk = Buffer.from('');
let currentChunkSize = 0;
let currentChunkStart = 0;
let currentChunk = 1;
let currentPosition = 0;
let uploadableChunk = new Uint8Array(client.CHUNK_SIZE);


const selfClient = this.client;

async function uploadChunk(lastUpload = false) {
if(chunksUploaded - 1 >= currentChunkStart / client.CHUNK_SIZE) {
const uploadChunk = async (lastUpload = false) => {
if(currentChunk <= chunksUploaded) {
return;
}

const start = currentChunkStart;
const end = currentChunkStart + currentChunkSize - 1;

if(!lastUpload || currentChunkStart !== 0) {
const start = ((currentChunk - 1) * client.CHUNK_SIZE);
let end = start + currentPosition - 1;

if(!lastUpload || currentChunk !== 1) {
apiHeaders['content-range'] = 'bytes ' + start + '-' + end + '/' + size;
}

let uploadableChunkTrimmed;

if(currentPosition + 1 >= client.CHUNK_SIZE) {
uploadableChunkTrimmed = uploadableChunk;
} else {
uploadableChunkTrimmed = new Uint8Array(currentPosition);
for(let i = 0; i <= currentPosition; i++) {
uploadableChunkTrimmed[i] = uploadableChunk[i];
}
}

if (id) {
apiHeaders['x-{{spec.title | caseLower }}-id'] = id;
}

payload['{{ parameter.name }}'] = {
type: 'file',
file: currentChunk,
filename: {{ parameter.name }}.filename,
size: currentChunkSize
};
payload['{{ parameter.name }}'] = { type: 'file', file: new File([uploadableChunkTrimmed], {{ parameter.name | caseCamel | escapeKeyword }}.filename), filename: {{ parameter.name | caseCamel | escapeKeyword }}.filename };

response = await selfClient.call('{{ method.method | caseLower }}', apiPath, apiHeaders, payload{% if method.type == 'location' %}, 'arraybuffer'{% endif %});
response = await this.client.call('{{ method.method | caseLower }}', apiPath, apiHeaders, payload{% if method.type == 'location' %}, 'arraybuffer'{% endif %});

if (!id) {
id = response['$id'];
}

if (onProgress !== null) {
onProgress({
$id: response['$id'],
progress: Math.min((start+client.CHUNK_SIZE) * client.CHUNK_SIZE, size) / size * 100,
progress: Math.min((currentChunk) * client.CHUNK_SIZE, size) / size * 100,
sizeUploaded: end+1,
chunksTotal: response['chunksTotal'],
chunksUploaded: response['chunksUploaded']
});
}

currentChunkStart += client.CHUNK_SIZE;
uploadableChunk = new Uint8Array(client.CHUNK_SIZE);
currentChunk++;
currentPosition = 0;
}

return await new Promise((resolve, reject) => {
const writeStream = new Stream.Writable();
writeStream._write = async (mainChunk, encoding, callback) => {
try {
// Segment incoming chunk into up to 5MB chunks
const mainChunkSize = Buffer.byteLength(mainChunk);
const chunksCount = Math.ceil(mainChunkSize / client.CHUNK_SIZE);
const chunks = [];

for(let i = 0; i < chunksCount; i++) {
const chunk = mainChunk.slice(i * client.CHUNK_SIZE, (i + 1) * client.CHUNK_SIZE);
chunks.push(chunk);
}

for (const chunk of chunks) {
const chunkSize = Buffer.byteLength(chunk);

if(chunkSize + currentChunkSize == client.CHUNK_SIZE) {
// Upload chunk
currentChunk = Buffer.concat([currentChunk, chunk]);
currentChunkSize = Buffer.byteLength(currentChunk);
await uploadChunk();
currentChunk = Buffer.from('');
currentChunkSize = 0;
} else if(chunkSize + currentChunkSize > client.CHUNK_SIZE) {
// Upload chunk, put rest into next chunk
const bytesToUpload = client.CHUNK_SIZE - currentChunkSize;
const newChunkSection = chunk.slice(0, bytesToUpload);
currentChunk = Buffer.concat([currentChunk, newChunkSection]);
currentChunkSize = Buffer.byteLength(currentChunk);
await uploadChunk();
currentChunk = chunk.slice(bytesToUpload, undefined);
currentChunkSize = chunkSize - bytesToUpload;
} else {
// Append into current chunk
currentChunk = Buffer.concat([currentChunk, chunk]);
currentChunkSize = chunkSize + currentChunkSize;
}
}

callback();
} catch (e) {
callback(e);
for await (const chunk of {{ parameter.name | caseCamel | escapeKeyword }}.stream) {
for(const b of chunk) {
uploadableChunk[currentPosition] = b;

currentPosition++;
if(currentPosition >= client.CHUNK_SIZE) {
await uploadChunk();
currentPosition = 0;
}
}
}

writeStream.on("finish", async () => {
if(currentChunkSize > 0) {
try {
await uploadChunk(true);
} catch (e) {
reject(e);
}
}

resolve(response);
});
if (currentPosition > 0) { // Check if there's any remaining data for the last chunk
await uploadChunk(true);
}

writeStream.on("error", (err) => {
reject(err);
});

{{ parameter.name | caseCamel | escapeKeyword }}.stream.pipe(writeStream);
});
return response;
{% endif %}
{% endfor %}
Loading
Loading