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

Add inline doc comments to the Web SDK template #721

Merged
merged 3 commits into from
Jun 4, 2024
Merged
Show file tree
Hide file tree
Changes from 2 commits
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
2 changes: 1 addition & 1 deletion templates/web/README.md.twig
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# {{ spec.title }} {{sdk.name}} SDK

![License](https://img.shields.io/github/license/{{ sdk.gitUserName|url_encode }}/{{ sdk.gitRepoName|url_encode }}.svg?style=flat-square)
![Version](https://img.shields.io/badge/api%20version-{{ spec.version|url_encode }}-blue.svg?style=flat-square)
![Version](https://img.shields.io/badge/api%20version-{{ spec.version | split('.') | slice(0,2) | join('.') ~ '.x' | url_encode }}-blue.svg?style=flat-square)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@Im-Madhur-Gupta Where did this change come from?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi, facing some medical issues currently, will get back to you in a couple of days.

Copy link
Contributor Author

@Im-Madhur-Gupta Im-Madhur-Gupta Apr 28, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@lohanidamodar Apologies for the delay in reply, I added this code while I was working on the ticket to fix some issue with the version batch but as I can see now we don't need it, hence I have reverted this change and pushed it.

[![Build Status](https://img.shields.io/travis/com/appwrite/sdk-generator?style=flat-square)](https://travis-ci.com/appwrite/sdk-generator)
{% if sdk.twitterHandle %}
[![Twitter Account](https://img.shields.io/twitter/follow/{{ sdk.twitterHandle }}?color=00acee&label=twitter&style=flat-square)](https://twitter.com/{{ sdk.twitterHandle }})
Expand Down
215 changes: 215 additions & 0 deletions templates/web/src/client.ts.twig
Original file line number Diff line number Diff line change
Expand Up @@ -3,83 +3,275 @@ import { fetch } from 'cross-fetch';
import { Models } from './models';
import { Service } from './service';

/**
* Payload type representing a key-value pair with string keys and any values.
*/
type Payload = {
[key: string]: any;
}

/**
* Headers type representing a key-value pair with string keys and string values.
*/
type Headers = {
[key: string]: string;
}

/**
* Realtime response structure with different types.
*/
type RealtimeResponse = {
/**
* Type of the response: 'error', 'event', 'connected', or 'response'.
*/
type: 'error' | 'event' | 'connected' | 'response';

/**
* Data associated with the response based on the response type.
*/
data: RealtimeResponseAuthenticated | RealtimeResponseConnected | RealtimeResponseError | RealtimeResponseEvent<unknown>;
}

/**
* Realtime request structure for authentication.
*/
type RealtimeRequest = {
/**
* Type of the request: 'authentication'.
*/
type: 'authentication';

/**
* Data required for authentication.
*/
data: RealtimeRequestAuthenticate;
}

/**
* Realtime event response structure with generic payload type.
*/
export type RealtimeResponseEvent<T extends unknown> = {
/**
* List of event names associated with the response.
*/
events: string[];

/**
* List of channel names associated with the response.
*/
channels: string[];

/**
* Timestamp indicating the time of the event.
*/
timestamp: number;

/**
* Payload containing event-specific data.
*/
payload: T;
}

/**
* Realtime response structure for errors.
*/
type RealtimeResponseError = {
/**
* Numeric error code indicating the type of error.
*/
code: number;

/**
* Error message describing the encountered error.
*/
message: string;
}

/**
* Realtime response structure for a successful connection.
*/
type RealtimeResponseConnected = {
/**
* List of channels the user is connected to.
*/
channels: string[];

/**
* User object representing the connected user (optional).
*/
user?: object;
}

/**
* Realtime response structure for authenticated connections.
*/
type RealtimeResponseAuthenticated = {
/**
* Destination channel for the response.
*/
to: string;

/**
* Boolean indicating the success of the authentication process.
*/
success: boolean;

/**
* User object representing the authenticated user.
*/
user: object;
}

/**
* Realtime request structure for authentication.
*/
type RealtimeRequestAuthenticate = {
/**
* Session identifier for authentication.
*/
session: string;
}

/**
* Realtime interface representing the structure of a realtime communication object.
*/
type Realtime = {
/**
* WebSocket instance for realtime communication.
*/
socket?: WebSocket;

/**
* Timeout duration for communication operations.
*/
timeout?: number;

/**
* URL for establishing the WebSocket connection.
*/
url?: string;

/**
* Last received message from the realtime server.
*/
lastMessage?: RealtimeResponse;

/**
* Set of channel names the client is subscribed to.
*/
channels: Set<string>;

/**
* Map of subscriptions containing channel names and corresponding callback functions.
*/
subscriptions: Map<number, {
channels: string[];
callback: (payload: RealtimeResponseEvent<any>) => void
}>;

/**
* Counter for managing subscriptions.
*/
subscriptionsCounter: number;

/**
* Boolean indicating whether automatic reconnection is enabled.
*/
reconnect: boolean;

/**
* Number of reconnection attempts made.
*/
reconnectAttempts: number;

/**
* Function to get the timeout duration for communication operations.
*/
getTimeout: () => number;

/**
* Function to establish a WebSocket connection.
*/
connect: () => void;

/**
* Function to create a new WebSocket instance.
*/
createSocket: () => void;

/**
* Function to clean up resources associated with specified channels.
*
* @param {string[]} channels - List of channel names to clean up.
*/
cleanUp: (channels: string[]) => void;

/**
* Function to handle incoming messages from the WebSocket connection.
*
* @param {MessageEvent} event - Event containing the received message.
*/
onMessage: (event: MessageEvent) => void;
}

/**
* Type representing upload progress information.
*/
export type UploadProgress = {
/**
* Identifier for the upload progress.
*/
$id: string;

/**
* Current progress of the upload (in percentage).
*/
progress: number;

/**
* Total size uploaded (in bytes) during the upload process.
*/
sizeUploaded: number;

/**
* Total number of chunks that need to be uploaded.
*/
chunksTotal: number;

/**
* Number of chunks that have been successfully uploaded.
*/
chunksUploaded: number;
}

/**
* Exception thrown by the {{language.params.packageName}} package
*/
class {{spec.title | caseUcfirst}}Exception extends Error {
/**
* The error code associated with the exception.
*/
code: number;

/**
* The response string associated with the exception.
*/
response: string;

/**
* Error type.
* See [Error Types]({{sdk.url}}/docs/response-codes#errorTypes) for more information.
*/
type: string;

/**
* Initializes a {{spec.title | caseUcfirst}} Exception.
*
* @param {string} message - The error message.
* @param {number} code - The error code. Default is 0.
* @param {string} type - The error type. Default is an empty string.
* @param {string} response - The response string. Default is an empty string.
*/
constructor(message: string, code: number = 0, type: string = '', response: string = '') {
super(message);
this.name = '{{spec.title | caseUcfirst}}Exception';
Expand All @@ -90,14 +282,24 @@ class {{spec.title | caseUcfirst}}Exception extends Error {
}
}

/**
* Client that handles requests to {{spec.title | caseUcfirst}}
*/
class Client {
/**
* Holds configuration such as project.
*/
config = {
endpoint: '{{ spec.endpoint }}',
endpointRealtime: '',
{% for header in spec.global.headers %}
{{ header.key | caseLower }}: '',
{% endfor %}
};

/**
* Custom headers for API requests.
*/
headers: Headers = {
'x-sdk-name': '{{ sdk.name }}',
'x-sdk-platform': '{{ sdk.platform }}',
Expand Down Expand Up @@ -336,6 +538,19 @@ class Client {
}
}

/**
* Call API endpoint with the specified method, URL, headers, and parameters.
*
* @param {string} method - HTTP method (e.g., 'GET', 'POST', 'PUT', 'DELETE').
* @param {URL} url - The URL of the API endpoint.
* @param {Headers} headers - Custom headers for the API request.
* @param {Payload} params - Request parameters.
* @returns {Promise<any>} - A promise that resolves with the response data.
*
* @typedef {Object} Payload - Request payload data.
* @property {string} key - The key.
* @property {string} value - The value.
*/
async call(method: string, url: URL, headers: Headers = {}, params: Payload = {}): Promise<any> {
method = method.toUpperCase();

Expand Down
23 changes: 21 additions & 2 deletions templates/web/src/id.ts.twig
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
/**
* Helper class to generate ID strings for resources.
*/
export class ID {
// Generate an hex ID based on timestamp
// Recreated from https://www.php.net/manual/en/function.uniqid.php
/**
* Generate an hex ID based on timestamp.
* Recreated from https://www.php.net/manual/en/function.uniqid.php
*
* @returns {string}
*/
static #hexTimestamp(): string {
const now = new Date();
const sec = Math.floor(now.getTime() / 1000);
Expand All @@ -11,10 +18,22 @@ export class ID {
return hexTimestamp;
}

/**
* Uses the provided ID as the ID for the resource.
*
* @param {string} id
* @returns {string}
*/
public static custom(id: string): string {
return id
}

/**
* Have Appwrite generate a unique ID for you.
*
* @param {number} padding. Default is 7.
* @returns {string}
*/
public static unique(padding: number = 7): string {
// Generate a unique ID with padding to have a longer ID
const baseId = ID.#hexTimestamp();
Expand Down
7 changes: 7 additions & 0 deletions templates/web/src/index.ts.twig
Original file line number Diff line number Diff line change
@@ -1,3 +1,10 @@
/**
* {{spec.title | caseUcfirst}} {{sdk.name}} SDK
*
* This SDK is compatible with Appwrite server version {{spec.version | split('.') | slice(0,2) | join('.') ~ '.x' }}.
* For older versions, please check
* [previous releases](https://github.com/{{sdk.gitUserName}}/{{sdk.gitRepoName}}/releases).
*/
export { Client, Query, {{spec.title | caseUcfirst}}Exception } from './client';
{% for service in spec.services %}
export { {{service.name | caseUcfirst}} } from './services/{{service.name | caseDash}}';
Expand Down
3 changes: 3 additions & 0 deletions templates/web/src/models.ts.twig
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
/**
* {{spec.title | caseUcfirst}} Models
*/
export namespace Models {
{% for definition in spec.definitions %}
/**
Expand Down
Loading