1
0
Fork 0
mirror of synced 2024-07-02 05:00:33 +12:00

Merge pull request #4672 from appwrite/test-storage-projects

feat: move project endpoint to another service
This commit is contained in:
Christy Jacob 2022-11-15 14:45:41 +05:30 committed by GitHub
commit 5b32f6d9a9
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
16 changed files with 270 additions and 219 deletions

View file

@ -108,6 +108,19 @@ return [
'optional' => false,
'icon' => '',
],
'project' => [
'key' => 'project',
'name' => 'Project',
'subtitle' => 'The Project service allows you to manage all the projects in your Appwrite server.',
'description' => '',
'controller' => 'api/project.php',
'sdk' => true,
'docs' => true,
'docsUrl' => '',
'tests' => false,
'optional' => false,
'icon' => '',
],
'storage' => [
'key' => 'storage',
'name' => 'Storage',

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1,111 @@
<?php
use Appwrite\Utopia\Response;
use Utopia\App;
use Utopia\Database\Database;
use Utopia\Database\DateTime;
use Utopia\Database\Document;
use Utopia\Database\Query;
use Utopia\Database\Validator\Authorization;
use Utopia\Validator\WhiteList;
App::get('/v1/project/usage')
->desc('Get usage stats for a project')
->groups(['api'])
->label('scope', 'projects.read')
->label('sdk.auth', [APP_AUTH_TYPE_ADMIN])
->label('sdk.namespace', 'project')
->label('sdk.method', 'getUsage')
->label('sdk.response.code', Response::STATUS_CODE_OK)
->label('sdk.response.type', Response::CONTENT_TYPE_JSON)
->label('sdk.response.model', Response::MODEL_USAGE_PROJECT)
->param('range', '30d', new WhiteList(['24h', '7d', '30d', '90d'], true), 'Date range.', true)
->inject('response')
->inject('dbForProject')
->action(function (string $range, Response $response, Database $dbForProject) {
$usage = [];
if (App::getEnv('_APP_USAGE_STATS', 'enabled') == 'enabled') {
$periods = [
'24h' => [
'period' => '30m',
'limit' => 48,
],
'7d' => [
'period' => '1d',
'limit' => 7,
],
'30d' => [
'period' => '1d',
'limit' => 30,
],
'90d' => [
'period' => '1d',
'limit' => 90,
],
];
$metrics = [
'project.$all.network.requests',
'project.$all.network.bandwidth',
'project.$all.storage.size',
'users.$all.count.total',
'collections.$all.count.total',
'documents.$all.count.total',
'executions.$all.compute.total',
];
$stats = [];
Authorization::skip(function () use ($dbForProject, $periods, $range, $metrics, &$stats) {
foreach ($metrics as $metric) {
$limit = $periods[$range]['limit'];
$period = $periods[$range]['period'];
$requestDocs = $dbForProject->find('stats', [
Query::equal('period', [$period]),
Query::equal('metric', [$metric]),
Query::limit($limit),
Query::orderDesc('time'),
]);
$stats[$metric] = [];
foreach ($requestDocs as $requestDoc) {
$stats[$metric][] = [
'value' => $requestDoc->getAttribute('value'),
'date' => $requestDoc->getAttribute('time'),
];
}
// backfill metrics with empty values for graphs
$backfill = $limit - \count($requestDocs);
while ($backfill > 0) {
$last = $limit - $backfill - 1; // array index of last added metric
$diff = match ($period) { // convert period to seconds for unix timestamp math
'30m' => 1800,
'1d' => 86400,
};
$stats[$metric][] = [
'value' => 0,
'date' => DateTime::formatTz(DateTime::addSeconds(new \DateTime($stats[$metric][$last]['date'] ?? null), -1 * $diff)),
];
$backfill--;
}
$stats[$metric] = array_reverse($stats[$metric]);
}
});
$usage = new Document([
'range' => $range,
'requests' => $stats[$metrics[0]] ?? [],
'network' => $stats[$metrics[1]] ?? [],
'storage' => $stats[$metrics[2]] ?? [],
'users' => $stats[$metrics[3]] ?? [],
'collections' => $stats[$metrics[4]] ?? [],
'documents' => $stats[$metrics[5]] ?? [],
'executions' => $stats[$metrics[6]] ?? [],
]);
}
$response->dynamic($usage, Response::MODEL_USAGE_PROJECT);
});

View file

@ -22,11 +22,9 @@ use Utopia\Database\DateTime;
use Utopia\Database\Permission;
use Utopia\Database\Query;
use Utopia\Database\Role;
use Utopia\Database\Validator\Authorization;
use Utopia\Database\Validator\DatetimeValidator;
use Utopia\Database\Validator\UID;
use Utopia\Domains\Domain;
use Utopia\Registry\Registry;
use Appwrite\Extend\Exception;
use Appwrite\Utopia\Database\Validator\Queries\Projects;
use Utopia\Cache\Cache;
@ -250,118 +248,6 @@ App::get('/v1/projects/:projectId')
$response->dynamic($project, Response::MODEL_PROJECT);
});
App::get('/v1/projects/:projectId/usage')
->desc('Get usage stats for a project')
->groups(['api', 'projects'])
->label('scope', 'projects.read')
->label('sdk.auth', [APP_AUTH_TYPE_ADMIN])
->label('sdk.namespace', 'projects')
->label('sdk.method', 'getUsage')
->label('sdk.response.code', Response::STATUS_CODE_OK)
->label('sdk.response.type', Response::CONTENT_TYPE_JSON)
->label('sdk.response.model', Response::MODEL_USAGE_PROJECT)
->param('projectId', '', new UID(), 'Project unique ID.')
->param('range', '30d', new WhiteList(['24h', '7d', '30d', '90d'], true), 'Date range.', true)
->inject('response')
->inject('dbForConsole')
->inject('dbForProject')
->inject('register')
->action(function (string $projectId, string $range, Response $response, Database $dbForConsole, Database $dbForProject, Registry $register) {
$project = $dbForConsole->getDocument('projects', $projectId);
if ($project->isEmpty()) {
throw new Exception(Exception::PROJECT_NOT_FOUND);
}
$usage = [];
if (App::getEnv('_APP_USAGE_STATS', 'enabled') == 'enabled') {
$periods = [
'24h' => [
'period' => '30m',
'limit' => 48,
],
'7d' => [
'period' => '1d',
'limit' => 7,
],
'30d' => [
'period' => '1d',
'limit' => 30,
],
'90d' => [
'period' => '1d',
'limit' => 90,
],
];
$dbForProject->setNamespace("_{$project->getInternalId()}");
$metrics = [
'project.$all.network.requests',
'project.$all.network.bandwidth',
'project.$all.storage.size',
'users.$all.count.total',
'collections.$all.count.total',
'documents.$all.count.total',
'executions.$all.compute.total',
];
$stats = [];
Authorization::skip(function () use ($dbForProject, $periods, $range, $metrics, &$stats) {
foreach ($metrics as $metric) {
$limit = $periods[$range]['limit'];
$period = $periods[$range]['period'];
$requestDocs = $dbForProject->find('stats', [
Query::equal('period', [$period]),
Query::equal('metric', [$metric]),
Query::limit($limit),
Query::orderDesc('time'),
]);
$stats[$metric] = [];
foreach ($requestDocs as $requestDoc) {
$stats[$metric][] = [
'value' => $requestDoc->getAttribute('value'),
'date' => $requestDoc->getAttribute('time'),
];
}
// backfill metrics with empty values for graphs
$backfill = $limit - \count($requestDocs);
while ($backfill > 0) {
$last = $limit - $backfill - 1; // array index of last added metric
$diff = match ($period) { // convert period to seconds for unix timestamp math
'30m' => 1800,
'1d' => 86400,
};
$stats[$metric][] = [
'value' => 0,
'date' => DateTime::formatTz(DateTime::addSeconds(new \DateTime($stats[$metric][$last]['date'] ?? null), -1 * $diff)),
];
$backfill--;
}
$stats[$metric] = array_reverse($stats[$metric]);
}
});
$usage = new Document([
'range' => $range,
'requests' => $stats[$metrics[0]] ?? [],
'network' => $stats[$metrics[1]] ?? [],
'storage' => $stats[$metrics[2]] ?? [],
'users' => $stats[$metrics[3]] ?? [],
'collections' => $stats[$metrics[4]] ?? [],
'documents' => $stats[$metrics[5]] ?? [],
'executions' => $stats[$metrics[6]] ?? [],
]);
}
$response->dynamic($usage, Response::MODEL_USAGE_PROJECT);
});
App::patch('/v1/projects/:projectId')
->desc('Update Project')
->groups(['api', 'projects'])

View file

@ -34,13 +34,11 @@ $usageStatsEnabled = $this->getParam('usageStatsEnabled', true);
data-analytics-event="click"
data-analytics-category="console"
data-analytics-label="Usage 24h"
data-service="projects.getUsage"
data-event="submit"
data-scope="console"
data-service="project.getUsage"
data-name="usage"
data-param-project-id="{{router.params.project}}"
data-param-range="24h"
data-scope="console">
data-scope="sdk">
<button class="tick">24h</button>
</form>
@ -51,12 +49,11 @@ $usageStatsEnabled = $this->getParam('usageStatsEnabled', true);
data-analytics-event="click"
data-analytics-category="console"
data-analytics-label="Usage 30d"
data-service="projects.getUsage"
data-service="project.getUsage"
data-event="submit"
data-scope="console"
data-name="usage"
data-param-project-id="{{router.params.project}}"
data-scope="console">
data-param-range="30d"
data-scope="sdk">
<button class="tick">30d</button>
</form>
@ -67,13 +64,11 @@ $usageStatsEnabled = $this->getParam('usageStatsEnabled', true);
data-analytics-event="click"
data-analytics-category="console"
data-analytics-label="Usage 90d"
data-service="projects.getUsage"
data-service="project.getUsage"
data-event="submit"
data-scope="console"
data-name="usage"
data-param-project-id="{{router.params.project}}"
data-param-range="90d"
data-scope="console">
data-scope="sdk">
<button class="tick">90d</button>
</form>
@ -82,12 +77,11 @@ $usageStatsEnabled = $this->getParam('usageStatsEnabled', true);
<?php endif;?>
</div>
<div
data-service="projects.getUsage"
data-service="project.getUsage"
data-event="load"
data-scope="console"
data-name="usage"
data-param-project-id="{{router.params.project}}"
data-param-range="30d">
data-param-range="30d"
data-scope="sdk">
<?php if (!$graph && $usageStatsEnabled): ?>
<div class="box dashboard">
<div class="row responsive">

File diff suppressed because one or more lines are too long

View file

@ -12,7 +12,7 @@ Service.CHUNK_SIZE=5*1024*1024;class Query{}
Query.equal=(attribute,value)=>Query.addQuery(attribute,"equal",value);Query.notEqual=(attribute,value)=>Query.addQuery(attribute,"notEqual",value);Query.lessThan=(attribute,value)=>Query.addQuery(attribute,"lessThan",value);Query.lessThanEqual=(attribute,value)=>Query.addQuery(attribute,"lessThanEqual",value);Query.greaterThan=(attribute,value)=>Query.addQuery(attribute,"greaterThan",value);Query.greaterThanEqual=(attribute,value)=>Query.addQuery(attribute,"greaterThanEqual",value);Query.search=(attribute,value)=>Query.addQuery(attribute,"search",value);Query.orderDesc=(attribute)=>`orderDesc("${attribute}")`;Query.orderAsc=(attribute)=>`orderAsc("${attribute}")`;Query.cursorAfter=(documentId)=>`cursorAfter("${documentId}")`;Query.cursorBefore=(documentId)=>`cursorBefore("${documentId}")`;Query.limit=(limit)=>`limit(${limit})`;Query.offset=(offset)=>`offset(${offset})`;Query.addQuery=(attribute,method,value)=>value instanceof Array?`${method}("${attribute}", [${value
.map((v) => Query.parseValues(v))
.join(",")}])`:`${method}("${attribute}", [${Query.parseValues(value)}])`;Query.parseValues=(value)=>typeof value==="string"||value instanceof String?`"${value}"`:`${value}`;class AppwriteException extends Error{constructor(message,code=0,type='',response=''){super(message);this.name='AppwriteException';this.message=message;this.code=code;this.type=type;this.response=response;}}
class Client{constructor(){this.config={endpoint:'https://HOSTNAME/v1',endpointRealtime:'',project:'',key:'',jwt:'',locale:'',mode:'',};this.headers={'x-sdk-name':'Console','x-sdk-platform':'console','x-sdk-language':'web','x-sdk-version':'7.0.0','X-Appwrite-Response-Format':'1.0.0',};this.realtime={socket:undefined,timeout:undefined,url:'',channels:new Set(),subscriptions:new Map(),subscriptionsCounter:0,reconnect:true,reconnectAttempts:0,lastMessage:undefined,connect:()=>{clearTimeout(this.realtime.timeout);this.realtime.timeout=window===null||window===void 0?void 0:window.setTimeout(()=>{this.realtime.createSocket();},50);},getTimeout:()=>{switch(true){case this.realtime.reconnectAttempts<5:return 1000;case this.realtime.reconnectAttempts<15:return 5000;case this.realtime.reconnectAttempts<100:return 10000;default:return 60000;}},createSocket:()=>{var _a,_b;if(this.realtime.channels.size<1)
class Client{constructor(){this.config={endpoint:'https://HOSTNAME/v1',endpointRealtime:'',project:'',key:'',jwt:'',locale:'',mode:'',};this.headers={'x-sdk-name':'Console','x-sdk-platform':'console','x-sdk-language':'web','x-sdk-version':'7.1.0','X-Appwrite-Response-Format':'1.0.0',};this.realtime={socket:undefined,timeout:undefined,url:'',channels:new Set(),subscriptions:new Map(),subscriptionsCounter:0,reconnect:true,reconnectAttempts:0,lastMessage:undefined,connect:()=>{clearTimeout(this.realtime.timeout);this.realtime.timeout=window===null||window===void 0?void 0:window.setTimeout(()=>{this.realtime.createSocket();},50);},getTimeout:()=>{switch(true){case this.realtime.reconnectAttempts<5:return 1000;case this.realtime.reconnectAttempts<15:return 5000;case this.realtime.reconnectAttempts<100:return 10000;default:return 60000;}},createSocket:()=>{var _a,_b;if(this.realtime.channels.size<1)
return;const channels=new URLSearchParams();channels.set('project',this.config.project);this.realtime.channels.forEach(channel=>{channels.append('channels[]',channel);});const url=this.config.endpointRealtime+'/realtime?'+channels.toString();if(url!==this.realtime.url||!this.realtime.socket||((_a=this.realtime.socket)===null||_a===void 0?void 0:_a.readyState)>WebSocket.OPEN){if(this.realtime.socket&&((_b=this.realtime.socket)===null||_b===void 0?void 0:_b.readyState)<WebSocket.CLOSING){this.realtime.reconnect=false;this.realtime.socket.close();}
this.realtime.url=url;this.realtime.socket=new WebSocket(url);this.realtime.socket.addEventListener('message',this.realtime.onMessage);this.realtime.socket.addEventListener('open',_event=>{this.realtime.reconnectAttempts=0;});this.realtime.socket.addEventListener('close',event=>{var _a,_b,_c;if(!this.realtime.reconnect||(((_b=(_a=this.realtime)===null||_a===void 0?void 0:_a.lastMessage)===null||_b===void 0?void 0:_b.type)==='error'&&((_c=this.realtime)===null||_c===void 0?void 0:_c.lastMessage.data).code===1008)){this.realtime.reconnect=true;return;}
const timeout=this.realtime.getTimeout();console.error(`Realtime got disconnected. Reconnect will be attempted in ${timeout / 1000} seconds.`,event.reason);setTimeout(()=>{this.realtime.reconnectAttempts++;this.realtime.createSocket();},timeout);});}},onMessage:(event)=>{var _a,_b;try{const message=JSON.parse(event.data);this.realtime.lastMessage=message;switch(message.type){case'connected':const cookie=JSON.parse((_a=window.localStorage.getItem('cookieFallback'))!==null&&_a!==void 0?_a:'{}');const session=cookie===null||cookie===void 0?void 0:cookie[`a_session_${this.config.project}`];const messageData=message.data;if(session&&!messageData.user){(_b=this.realtime.socket)===null||_b===void 0?void 0:_b.send(JSON.stringify({type:'authentication',data:{session}}));}
@ -458,7 +458,7 @@ let path='/functions/{functionId}/deployments/{deploymentId}'.replace('{function
deleteDeployment(functionId,deploymentId){return __awaiter(this,void 0,void 0,function*(){if(typeof functionId==='undefined'){throw new AppwriteException('Missing required parameter: "functionId"');}
if(typeof deploymentId==='undefined'){throw new AppwriteException('Missing required parameter: "deploymentId"');}
let path='/functions/{functionId}/deployments/{deploymentId}'.replace('{functionId}',functionId).replace('{deploymentId}',deploymentId);let payload={};const uri=new URL(this.client.config.endpoint+path);return yield this.client.call('delete',uri,{'content-type':'application/json',},payload);});}
retryBuild(functionId,deploymentId,buildId){return __awaiter(this,void 0,void 0,function*(){if(typeof functionId==='undefined'){throw new AppwriteException('Missing required parameter: "functionId"');}
createBuild(functionId,deploymentId,buildId){return __awaiter(this,void 0,void 0,function*(){if(typeof functionId==='undefined'){throw new AppwriteException('Missing required parameter: "functionId"');}
if(typeof deploymentId==='undefined'){throw new AppwriteException('Missing required parameter: "deploymentId"');}
if(typeof buildId==='undefined'){throw new AppwriteException('Missing required parameter: "buildId"');}
let path='/functions/{functionId}/deployments/{deploymentId}/builds/{buildId}'.replace('{functionId}',functionId).replace('{deploymentId}',deploymentId).replace('{buildId}',buildId);let payload={};const uri=new URL(this.client.config.endpoint+path);return yield this.client.call('post',uri,{'content-type':'application/json',},payload);});}
@ -501,6 +501,8 @@ get(){return __awaiter(this,void 0,void 0,function*(){let path='/health';let pay
getAntivirus(){return __awaiter(this,void 0,void 0,function*(){let path='/health/anti-virus';let payload={};const uri=new URL(this.client.config.endpoint+path);return yield this.client.call('get',uri,{'content-type':'application/json',},payload);});}
getCache(){return __awaiter(this,void 0,void 0,function*(){let path='/health/cache';let payload={};const uri=new URL(this.client.config.endpoint+path);return yield this.client.call('get',uri,{'content-type':'application/json',},payload);});}
getDB(){return __awaiter(this,void 0,void 0,function*(){let path='/health/db';let payload={};const uri=new URL(this.client.config.endpoint+path);return yield this.client.call('get',uri,{'content-type':'application/json',},payload);});}
getPubSub(){return __awaiter(this,void 0,void 0,function*(){let path='/health/pubsub';let payload={};const uri=new URL(this.client.config.endpoint+path);return yield this.client.call('get',uri,{'content-type':'application/json',},payload);});}
getQueue(){return __awaiter(this,void 0,void 0,function*(){let path='/health/queue';let payload={};const uri=new URL(this.client.config.endpoint+path);return yield this.client.call('get',uri,{'content-type':'application/json',},payload);});}
getQueueCertificates(){return __awaiter(this,void 0,void 0,function*(){let path='/health/queue/certificates';let payload={};const uri=new URL(this.client.config.endpoint+path);return yield this.client.call('get',uri,{'content-type':'application/json',},payload);});}
getQueueFunctions(){return __awaiter(this,void 0,void 0,function*(){let path='/health/queue/functions';let payload={};const uri=new URL(this.client.config.endpoint+path);return yield this.client.call('get',uri,{'content-type':'application/json',},payload);});}
getQueueLogs(){return __awaiter(this,void 0,void 0,function*(){let path='/health/queue/logs';let payload={};const uri=new URL(this.client.config.endpoint+path);return yield this.client.call('get',uri,{'content-type':'application/json',},payload);});}
@ -515,6 +517,9 @@ listCountriesEU(){return __awaiter(this,void 0,void 0,function*(){let path='/loc
listCountriesPhones(){return __awaiter(this,void 0,void 0,function*(){let path='/locale/countries/phones';let payload={};const uri=new URL(this.client.config.endpoint+path);return yield this.client.call('get',uri,{'content-type':'application/json',},payload);});}
listCurrencies(){return __awaiter(this,void 0,void 0,function*(){let path='/locale/currencies';let payload={};const uri=new URL(this.client.config.endpoint+path);return yield this.client.call('get',uri,{'content-type':'application/json',},payload);});}
listLanguages(){return __awaiter(this,void 0,void 0,function*(){let path='/locale/languages';let payload={};const uri=new URL(this.client.config.endpoint+path);return yield this.client.call('get',uri,{'content-type':'application/json',},payload);});}}
class Project extends Service{constructor(client){super(client);}
getUsage(range){return __awaiter(this,void 0,void 0,function*(){let path='/project/usage';let payload={};if(typeof range!=='undefined'){payload['range']=range;}
const uri=new URL(this.client.config.endpoint+path);return yield this.client.call('get',uri,{'content-type':'application/json',},payload);});}}
class Projects extends Service{constructor(client){super(client);}
list(queries,search){return __awaiter(this,void 0,void 0,function*(){let path='/projects';let payload={};if(typeof queries!=='undefined'){payload['queries']=queries;}
if(typeof search!=='undefined'){payload['search']=search;}
@ -638,9 +643,6 @@ if(typeof status==='undefined'){throw new AppwriteException('Missing required pa
let path='/projects/{projectId}/service'.replace('{projectId}',projectId);let payload={};if(typeof service!=='undefined'){payload['service']=service;}
if(typeof status!=='undefined'){payload['status']=status;}
const uri=new URL(this.client.config.endpoint+path);return yield this.client.call('patch',uri,{'content-type':'application/json',},payload);});}
getUsage(projectId,range){return __awaiter(this,void 0,void 0,function*(){if(typeof projectId==='undefined'){throw new AppwriteException('Missing required parameter: "projectId"');}
let path='/projects/{projectId}/usage'.replace('{projectId}',projectId);let payload={};if(typeof range!=='undefined'){payload['range']=range;}
const uri=new URL(this.client.config.endpoint+path);return yield this.client.call('get',uri,{'content-type':'application/json',},payload);});}
listWebhooks(projectId){return __awaiter(this,void 0,void 0,function*(){if(typeof projectId==='undefined'){throw new AppwriteException('Missing required parameter: "projectId"');}
let path='/projects/{projectId}/webhooks'.replace('{projectId}',projectId);let payload={};const uri=new URL(this.client.config.endpoint+path);return yield this.client.call('get',uri,{'content-type':'application/json',},payload);});}
createWebhook(projectId,name,events,url,security,httpUser,httpPass){return __awaiter(this,void 0,void 0,function*(){if(typeof projectId==='undefined'){throw new AppwriteException('Missing required parameter: "projectId"');}
@ -957,15 +959,17 @@ let path='/users/{userId}/verification/phone'.replace('{userId}',userId);let pay
const uri=new URL(this.client.config.endpoint+path);return yield this.client.call('patch',uri,{'content-type':'application/json',},payload);});}}
class Permission{}
Permission.read=(role)=>{return`read("${role}")`;};Permission.write=(role)=>{return`write("${role}")`;};Permission.create=(role)=>{return`create("${role}")`;};Permission.update=(role)=>{return`update("${role}")`;};Permission.delete=(role)=>{return`delete("${role}")`;};class Role{static any(){return'any';}
static user(id){return`user:${id}`;}
static users(){return'users';}
static user(id,status=''){if(status===''){return`user:${id}`;}
return`user:${id}/${status}`;}
static users(status=''){if(status===''){return'users';}
return`users/${status}`;}
static guests(){return'guests';}
static team(id,role=''){if(role===''){return`team:${id}`;}
return`team:${id}/${role}`;}
static status(status){return`status:${status}`;}}
static member(id){return`member:${id}`;}}
class ID{static custom(id){return id;}
static unique(){return'unique()';}}
exports.Account=Account;exports.AppwriteException=AppwriteException;exports.Avatars=Avatars;exports.Client=Client;exports.Databases=Databases;exports.Functions=Functions;exports.Health=Health;exports.ID=ID;exports.Locale=Locale;exports.Permission=Permission;exports.Projects=Projects;exports.Query=Query;exports.Role=Role;exports.Storage=Storage;exports.Teams=Teams;exports.Users=Users;Object.defineProperty(exports,'__esModule',{value:true});})(this.Appwrite=this.Appwrite||{},null,window);(function(global,factory){typeof exports==='object'&&typeof module!=='undefined'?module.exports=factory():typeof define==='function'&&define.amd?define(factory):(global=typeof globalThis!=='undefined'?globalThis:global||self,global.Chart=factory());})(this,(function(){'use strict';function noop(){}
exports.Account=Account;exports.AppwriteException=AppwriteException;exports.Avatars=Avatars;exports.Client=Client;exports.Databases=Databases;exports.Functions=Functions;exports.Health=Health;exports.ID=ID;exports.Locale=Locale;exports.Permission=Permission;exports.Project=Project;exports.Projects=Projects;exports.Query=Query;exports.Role=Role;exports.Storage=Storage;exports.Teams=Teams;exports.Users=Users;Object.defineProperty(exports,'__esModule',{value:true});})(this.Appwrite=this.Appwrite||{},null,window);(function(global,factory){typeof exports==='object'&&typeof module!=='undefined'?module.exports=factory():typeof define==='function'&&define.amd?define(factory):(global=typeof globalThis!=='undefined'?globalThis:global||self,global.Chart=factory());})(this,(function(){'use strict';function noop(){}
const uid=(function(){let id=0;return function(){return id++;};}());function isNullOrUndef(value){return value===null||typeof value==='undefined';}
function isArray(value){if(Array.isArray&&Array.isArray(value)){return true;}
const type=Object.prototype.toString.call(value);if(type.slice(0,7)==='[object'&&type.slice(-6)==='Array]'){return true;}

File diff suppressed because one or more lines are too long

View file

@ -96,7 +96,7 @@
'x-sdk-name': 'Console',
'x-sdk-platform': 'console',
'x-sdk-language': 'web',
'x-sdk-version': '7.0.0',
'x-sdk-version': '7.1.0',
'X-Appwrite-Response-Format': '1.0.0',
};
this.realtime = {
@ -500,7 +500,7 @@
});
}
/**
* Update Account Email
* Update Email
*
* Update currently logged in user account email address. After changing user
* address, the user confirmation status will get reset. A new confirmation
@ -539,7 +539,7 @@
});
}
/**
* Create Account JWT
* Create JWT
*
* Use this endpoint to create a JSON Web Token. You can use the resulting JWT
* to authenticate on behalf of the current user when working with the
@ -561,7 +561,7 @@
});
}
/**
* List Account Logs
* List Logs
*
* Get currently logged in user list of latest security activity logs. Each
* log returns user IP address, location and date and time of log.
@ -584,7 +584,7 @@
});
}
/**
* Update Account Name
* Update Name
*
* Update currently logged in user account name.
*
@ -609,7 +609,7 @@
});
}
/**
* Update Account Password
* Update Password
*
* Update currently logged in user password. For validation, user is required
* to pass in the new password, and the old password. For users created with
@ -640,7 +640,7 @@
});
}
/**
* Update Account Phone
* Update Phone
*
* Update the currently logged in user's phone number. After updating the
* phone number, the phone verification status will be reset. A confirmation
@ -694,7 +694,7 @@
});
}
/**
* Update Account Preferences
* Update Preferences
*
* Update currently logged in user account preferences. The object you pass is
* stored as is, and replaces any previous value. The maximum allowed prefs
@ -814,7 +814,7 @@
});
}
/**
* List Account Sessions
* List Sessions
*
* Get currently logged in user list of active sessions across different
* devices.
@ -833,7 +833,7 @@
});
}
/**
* Delete All Account Sessions
* Delete Sessions
*
* Delete all sessions from the user account and remove any sessions cookies
* from the end client.
@ -875,7 +875,7 @@
});
}
/**
* Create Account Session with Email
* Create Email Session
*
* Allow the user to login into their account by providing a valid email and
* password combination. This route will create a new session for the user.
@ -996,7 +996,7 @@
});
}
/**
* Create Account Session with OAuth2
* Create OAuth2 Session
*
* Allow the user to login to their account using the OAuth2 provider of their
* choice. Each OAuth2 provider should be enabled from the Appwrite console
@ -1119,7 +1119,7 @@
});
}
/**
* Get Session By ID
* Get Session
*
* Use this endpoint to get a logged in user's session using a Session ID.
* Inputting 'current' will return the current session being used.
@ -1142,7 +1142,7 @@
});
}
/**
* Update Session (Refresh Tokens)
* Update OAuth Session (Refresh Tokens)
*
* Access tokens have limited lifespan and expire to mitigate security risks.
* If session was created using an OAuth provider, this route can be used to
@ -1166,7 +1166,7 @@
});
}
/**
* Delete Account Session
* Delete Session
*
* Use this endpoint to log out the currently logged in user from all their
* account sessions across all of their different devices. When using the
@ -1191,7 +1191,7 @@
});
}
/**
* Update Account Status
* Update Status
*
* Block the currently logged in user account. Behind the scene, the user
* record is not deleted but permanently blocked from any access. To
@ -2527,9 +2527,7 @@
* List Documents
*
* Get a list of all the user's documents in a given collection. You can use
* the query params to filter your results. On admin mode, this endpoint will
* return a list of all of documents belonging to the provided collectionId.
* [Learn more about different API modes](/docs/admin).
* the query params to filter your results.
*
* @param {string} databaseId
* @param {string} collectionId
@ -3413,7 +3411,7 @@
});
}
/**
* Retry Build
* Create Build
*
*
* @param {string} functionId
@ -3422,7 +3420,7 @@
* @throws {AppwriteException}
* @returns {Promise}
*/
retryBuild(functionId, deploymentId, buildId) {
createBuild(functionId, deploymentId, buildId) {
return __awaiter(this, void 0, void 0, function* () {
if (typeof functionId === 'undefined') {
throw new AppwriteException('Missing required parameter: "functionId"');
@ -3445,9 +3443,7 @@
* List Executions
*
* Get a list of all the current user function execution logs. You can use the
* query params to filter your results. On admin mode, this endpoint will
* return a list of all of the project's executions. [Learn more about
* different API modes](/docs/admin).
* query params to filter your results.
*
* @param {string} functionId
* @param {string[]} queries
@ -3751,7 +3747,7 @@
/**
* Get Cache
*
* Check the Appwrite in-memory cache server is up and connection is
* Check the Appwrite in-memory cache servers are up and connection is
* successful.
*
* @throws {AppwriteException}
@ -3770,7 +3766,7 @@
/**
* Get DB
*
* Check the Appwrite database server is up and connection is successful.
* Check the Appwrite database servers are up and connection is successful.
*
* @throws {AppwriteException}
* @returns {Promise}
@ -3785,6 +3781,43 @@
}, payload);
});
}
/**
* Get PubSub
*
* Check the Appwrite pub-sub servers are up and connection is successful.
*
* @throws {AppwriteException}
* @returns {Promise}
*/
getPubSub() {
return __awaiter(this, void 0, void 0, function* () {
let path = '/health/pubsub';
let payload = {};
const uri = new URL(this.client.config.endpoint + path);
return yield this.client.call('get', uri, {
'content-type': 'application/json',
}, payload);
});
}
/**
* Get Queue
*
* Check the Appwrite queue messaging servers are up and connection is
* successful.
*
* @throws {AppwriteException}
* @returns {Promise}
*/
getQueue() {
return __awaiter(this, void 0, void 0, function* () {
let path = '/health/queue';
let payload = {};
const uri = new URL(this.client.config.endpoint + path);
return yield this.client.call('get', uri, {
'content-type': 'application/json',
}, payload);
});
}
/**
* Get Certificates Queue
*
@ -4048,6 +4081,33 @@
}
}
class Project extends Service {
constructor(client) {
super(client);
}
/**
* Get usage stats for a project
*
*
* @param {string} range
* @throws {AppwriteException}
* @returns {Promise}
*/
getUsage(range) {
return __awaiter(this, void 0, void 0, function* () {
let path = '/project/usage';
let payload = {};
if (typeof range !== 'undefined') {
payload['range'] = range;
}
const uri = new URL(this.client.config.endpoint + path);
return yield this.client.call('get', uri, {
'content-type': 'application/json',
}, payload);
});
}
}
class Projects extends Service {
constructor(client) {
super(client);
@ -4834,31 +4894,6 @@
}, payload);
});
}
/**
* Get usage stats for a project
*
*
* @param {string} projectId
* @param {string} range
* @throws {AppwriteException}
* @returns {Promise}
*/
getUsage(projectId, range) {
return __awaiter(this, void 0, void 0, function* () {
if (typeof projectId === 'undefined') {
throw new AppwriteException('Missing required parameter: "projectId"');
}
let path = '/projects/{projectId}/usage'.replace('{projectId}', projectId);
let payload = {};
if (typeof range !== 'undefined') {
payload['range'] = range;
}
const uri = new URL(this.client.config.endpoint + path);
return yield this.client.call('get', uri, {
'content-type': 'application/json',
}, payload);
});
}
/**
* List Webhooks
*
@ -5280,8 +5315,7 @@
* List Files
*
* Get a list of all the user files. You can use the query params to filter
* your results. On admin mode, this endpoint will return a list of all of the
* project's files. [Learn more about different API modes](/docs/admin).
* your results.
*
* @param {string} bucketId
* @param {string[]} queries
@ -5683,9 +5717,6 @@
* Get a list of all the teams in which the current user is a member. You can
* use the parameters to filter your results.
*
* In admin mode, this endpoint returns a list of all the teams in the current
* project. [Learn more about different API modes](/docs/admin).
*
* @param {string[]} queries
* @param {string} search
* @throws {AppwriteException}
@ -7002,11 +7033,17 @@
static any() {
return 'any';
}
static user(id) {
return `user:${id}`;
static user(id, status = '') {
if (status === '') {
return `user:${id}`;
}
return `user:${id}/${status}`;
}
static users() {
return 'users';
static users(status = '') {
if (status === '') {
return 'users';
}
return `users/${status}`;
}
static guests() {
return 'guests';
@ -7017,8 +7054,8 @@
}
return `team:${id}/${role}`;
}
static status(status) {
return `status:${status}`;
static member(id) {
return `member:${id}`;
}
}
@ -7041,6 +7078,7 @@
exports.ID = ID;
exports.Locale = Locale;
exports.Permission = Permission;
exports.Project = Project;
exports.Projects = Projects;
exports.Query = Query;
exports.Role = Role;

View file

@ -14,6 +14,7 @@
return {
client: client,
project: new Appwrite.Project(client),
account: new Appwrite.Account(client),
avatars: new Appwrite.Avatars(client),
databases: new Appwrite.Databases(client),

View file

@ -313,7 +313,7 @@ class ProjectsConsoleClientTest extends Scope
/**
* Test for SUCCESS
*/
$response = $this->client->call(Client::METHOD_GET, '/projects/' . $id . '/usage', array_merge([
$response = $this->client->call(Client::METHOD_GET, '/project/usage', array_merge([
'content-type' => 'application/json',
'x-appwrite-project' => $this->getProject()['$id'],
], $this->getHeaders()));