Skip to content

Storage List API #1610

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

Merged
merged 57 commits into from
May 28, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
57 commits
Select commit Hold shift + click to select a range
e52cc85
List API
fredzqm Mar 17, 2019
974b248
Update constants.ts
fredzqm Mar 17, 2019
0984bc3
always pass in prefix
fredzqm Mar 17, 2019
324a7ba
Merge branch 'fz/storage-list' of github.com:firebase/firebase-js-sdk…
fredzqm Mar 17, 2019
1f52804
clean up
fredzqm Mar 17, 2019
29ebc7c
more tests and clean up
fredzqm Mar 17, 2019
3071b84
more tests
fredzqm Mar 17, 2019
d1dad43
[AUTOMATED]: Prettier Code Styling
fredzqm Mar 17, 2019
b3585cb
fix test
fredzqm Mar 17, 2019
25b6169
[AUTOMATED]: Prettier Code Styling
fredzqm Mar 17, 2019
bedf0f8
Update .gitignore
fredzqm Mar 18, 2019
189184b
Update .gitignore
fredzqm Mar 18, 2019
dd8a2a7
Update constants.ts
fredzqm Mar 18, 2019
99954da
Update list.ts
fredzqm Mar 18, 2019
931eefd
Update reference.ts
fredzqm Mar 18, 2019
1c3ab63
Merge branch 'fz/storage-list' of github.com:firebase/firebase-js-sdk…
fredzqm Mar 18, 2019
a11ab95
clean up
fredzqm Mar 18, 2019
7e004b1
[AUTOMATED]: Prettier Code Styling
fredzqm Mar 18, 2019
1bc3aee
m
fredzqm Mar 18, 2019
49ec291
address comments
fredzqm Mar 19, 2019
2cd9edd
[AUTOMATED]: Prettier Code Styling
fredzqm Mar 19, 2019
0a86471
docs
fredzqm Mar 19, 2019
aa9d692
s/firebase.Promise/Promise
fredzqm Mar 20, 2019
ee3a184
nits
fredzqm Mar 20, 2019
a724f64
Merge branch 'fz/s/firebase.Promise/Promise' into fz/storage-list
fredzqm Mar 20, 2019
24dfd9a
remove unecessary type annotations
fredzqm Mar 21, 2019
ba28dbd
Merge branch 'fz/s/firebase.Promise/Promise' into fz/list-api
fredzqm Mar 21, 2019
43cde81
Merge remote-tracking branch 'origin/fz/storage-list' into fz/list-api
fredzqm Mar 21, 2019
9e901d2
last round
fredzqm Mar 21, 2019
4663ade
m
fredzqm Mar 21, 2019
b936dde
Merge remote-tracking branch 'origin/master' into fz/storage-list
fredzqm Mar 21, 2019
7d8889e
m
fredzqm Mar 21, 2019
ae0ceca
m
fredzqm Mar 21, 2019
8131c6e
Merge remote-tracking branch 'origin/master' into fz/storage-list
fredzqm Apr 16, 2019
e1f603c
m
fredzqm Apr 17, 2019
57f2584
m
fredzqm Apr 17, 2019
3935839
doc
fredzqm Apr 19, 2019
336de09
m
fredzqm Apr 19, 2019
8288325
more docs
fredzqm Apr 19, 2019
21759f7
more doc
fredzqm Apr 19, 2019
b651365
Merge remote-tracking branch 'origin/master' into fz/storage-list
fredzqm May 20, 2019
1f20d3a
add listAll
fredzqm May 20, 2019
31fe235
[AUTOMATED]: Prettier Code Styling
fredzqm May 20, 2019
2e052ea
doc
fredzqm May 20, 2019
325e84f
address comments
fredzqm May 21, 2019
8ea7bcf
m
fredzqm May 21, 2019
324f9a9
m
fredzqm May 21, 2019
ffb3569
m
fredzqm May 21, 2019
fd6ee14
Update index.d.ts
fredzqm May 22, 2019
035e760
Update reference.ts
fredzqm May 22, 2019
d201c91
Merge remote-tracking branch 'origin/master' into fz/storage-list
fredzqm May 22, 2019
4015d7b
[AUTOMATED]: Prettier Code Styling
fredzqm May 22, 2019
dff0f21
change log
fredzqm May 22, 2019
0fee0bb
mention rules version 2
fredzqm May 28, 2019
21d5f83
Merge remote-tracking branch 'origin/master' into fz/storage-list
fredzqm May 28, 2019
3f50d88
address comments
fredzqm May 28, 2019
4470649
Update toc.yaml
fredzqm May 28, 2019
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
79 changes: 79 additions & 0 deletions packages/firebase/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5484,6 +5484,85 @@ declare namespace firebase.storage {
* including if the object did not exist.
*/
updateMetadata(metadata: firebase.storage.SettableMetadata): Promise<any>;
/**
* List all items (files) and prefixes (folders) under this storage reference.
*
* This is a helper method for calling list() repeatedly until there are
* no more results. The default pagination size is 1000.
*
* Note: The results may not be consistent if objects are changed while this
* operation is running.
*
* Warning: listAll may potentially consume too many resources if there are
* too many results.
*
* @return A Promise that resolves with all the items and prefixes under
* the current storage reference. `prefixes` contains references to
* sub-directories and `items` contains references to objects in this
* folder. `nextPageToken` is never returned.
*/
listAll(): Promise<ListResult>;
/**
* List items (files) and prefixes (folders) under this storage reference.
*
* List API is only available for Firebase Rules Version 2.
*
* GCS is a key-blob store. Firebase Storage imposes the semantic of '/'
* delimited folder structure.
* Refer to GCS's List API if you want to learn more.
*
* To adhere to Firebase Rules's Semantics, Firebase Storage does not
* support objects whose paths end with "/" or contain two consecutive
* "/"s. Firebase Storage List API will filter these unsupported objects.
* list() may fail if there are too many unsupported objects in the bucket.
*
* @param options See ListOptions for details.
* @return A Promise that resolves with the items and prefixes.
* `prefixes` contains references to sub-folders and `items`
* contains references to objects in this folder. `nextPageToken`
* can be used to get the rest of the results.
*/
list(options?: ListOptions): Promise<ListResult>;
}

/**
* Result returned by list().
*/
interface ListResult {
/**
* References to prefixes (sub-folders). You can call list() on them to
* get its contents.
*
* Folders are implicit based on '/' in the object paths.
* For example, if a bucket has two objects '/a/b/1' and '/a/b/2', list('/a')
* will return '/a/b' as a prefix.
*/
prefixes: Reference[];
/**
* Objects in this directory.
* You can call getMetadate() and getDownloadUrl() on them.
*/
items: Reference[];
/**
* If set, there might be more results for this list. Use this token to resume the list.
*/
nextPageToken: string | null;
}

/**
* The options list() accepts.
*/
interface ListOptions {
/**
* If set, limits the total number of `prefixes` and `items` to return.
* The default and maximum maxResults is 1000.
*/
maxResults?: number | null;
/**
* The `nextPageToken` from a previous call to list(). If provided,
* listing is resumed from the previous position.
*/
pageToken?: string | null;
}

/**
Expand Down
12 changes: 12 additions & 0 deletions packages/storage-types/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,18 @@ export interface Reference {
storage: Storage;
toString(): string;
updateMetadata(metadata: SettableMetadata): Promise<FullMetadata>;
list(options?: ListOptions): Promise<ListResult>;
}

export interface ListResult {
prefixes: Reference[];
items: Reference[];
nextPageToken: string | null;
}

export interface ListOptions {
maxResults?: number | null;
pageToken?: string | null;
}

export interface SettableMetadata {
Expand Down
2 changes: 2 additions & 0 deletions packages/storage/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
- [Feature] Added the support for List API.

6 changes: 5 additions & 1 deletion packages/storage/src/implementation/args.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,8 @@
* limitations under the License.
*/
import * as errorsExports from './error';
import { errors } from './error';
import * as MetadataUtils from './metadata';
import * as ListOptionsUtils from './list';
import * as type from './type';

/**
Expand Down Expand Up @@ -117,6 +117,10 @@ export function metadataSpec(opt_optional?: boolean): ArgSpec {
return new ArgSpec(MetadataUtils.metadataValidator, opt_optional);
}

export function listOptionSpec(opt_optional?: boolean): ArgSpec {
return new ArgSpec(ListOptionsUtils.listOptionsValidator, opt_optional);
}

export function nonNegativeNumberSpec(): ArgSpec {
function validator(p: any) {
let valid = type.isNumber(p) && p >= 0;
Expand Down
115 changes: 115 additions & 0 deletions packages/storage/src/implementation/list.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
/**
* @license
* Copyright 2019 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/**
* @fileoverview Documentation for the listOptions and listResult format
*/
import { AuthWrapper } from './authwrapper';
import { Location } from './location';
import * as json from './json';
import * as type from './type';
import { ListResult } from '../list';

/**
* Represents the simplified object metadata returned by List API.
* Other fields are filtered because list in Firebase Rules does not grant
* the permission to read the metadata.
*/
interface ListMetadataResponse {
name: string;
bucket: string;
}

/**
* Represents the JSON response of List API.
*/
interface ListResultResponse {
prefixes: string[];
items: ListMetadataResponse[];
nextPageToken?: string;
}

const MAX_RESULTS_KEY = 'maxResults';
const MAX_MAX_RESULTS = 1000;
const PAGE_TOKEN_KEY = 'pageToken';
const PREFIXES_KEY = 'prefixes';
const ITEMS_KEY = 'items';

function fromBackendResponse(
authWrapper: AuthWrapper,
resource: ListResultResponse
): ListResult {
const listResult: ListResult = {
prefixes: [],
items: [],
nextPageToken: resource['nextPageToken']
};
if (resource[PREFIXES_KEY]) {
for (const path of resource[PREFIXES_KEY]) {
const pathWithoutTrailingSlash = path.replace(/\/$/, '');
const reference = authWrapper.makeStorageReference(
new Location(authWrapper.bucket(), pathWithoutTrailingSlash)
);
listResult.prefixes.push(reference);
}
}

if (resource[ITEMS_KEY]) {
for (const item of resource[ITEMS_KEY]) {
const reference = authWrapper.makeStorageReference(
new Location(authWrapper.bucket(), item['name'])
);
listResult.items.push(reference);
}
}
return listResult;
}

export function fromResponseString(
authWrapper: AuthWrapper,
resourceString: string
): ListResult | null {
const obj = json.jsonObjectOrNull(resourceString);
if (obj === null) {
return null;
}
const resource = obj as ListResultResponse;
return fromBackendResponse(authWrapper, resource);
}

export function listOptionsValidator(p: any) {
const validType = p && type.isObject(p);
if (!validType) {
throw 'Expected ListOptions object.';
}
for (const key in p) {
if (key === MAX_RESULTS_KEY) {
if (!type.isInteger(p[MAX_RESULTS_KEY]) || p[MAX_RESULTS_KEY] <= 0) {
throw 'Expected maxResults to be a positive number.';
}
if (p[MAX_RESULTS_KEY] > 1000) {
throw `Expected maxResults to be less than or equal to ${MAX_MAX_RESULTS}.`;
}
} else if (key === PAGE_TOKEN_KEY) {
if (p[PAGE_TOKEN_KEY] && !type.isString(p[PAGE_TOKEN_KEY])) {
throw 'Expected pageToken to be string.';
}
} else {
throw 'Unknown option: ' + key;
}
}
}
4 changes: 4 additions & 0 deletions packages/storage/src/implementation/location.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@ export class Location {
return this.path_;
}

get isRoot(): boolean {
return this.path.length === 0;
}

fullServerUrl(): string {
let encode = encodeURIComponent;
return '/b/' + encode(this.bucket) + '/o/' + encode(this.path);
Expand Down
50 changes: 50 additions & 0 deletions packages/storage/src/implementation/requests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
*/

import { Metadata } from '../metadata';
import { ListResult } from '../list';

import * as array from './array';
import { AuthWrapper } from './authwrapper';
Expand All @@ -28,6 +29,7 @@ import * as errorsExports from './error';
import { FirebaseStorageError } from './error';
import { Location } from './location';
import * as MetadataUtils from './metadata';
import * as ListResultUtils from './list';
import * as object from './object';
import { RequestInfo } from './requestinfo';
import * as type from './type';
Expand Down Expand Up @@ -59,6 +61,17 @@ export function metadataHandler(
return handler;
}

export function listHandler(
authWrapper: AuthWrapper
): (p1: XhrIo, p2: string) => ListResult {
function handler(xhr: XhrIo, text: string): ListResult {
const listResult = ListResultUtils.fromResponseString(authWrapper, text);
handlerCheck(listResult !== null);
return listResult as ListResult;
}
return handler;
}

export function downloadUrlHandler(
authWrapper: AuthWrapper,
mappings: MetadataUtils.Mappings
Expand Down Expand Up @@ -143,6 +156,43 @@ export function getMetadata(
return requestInfo;
}

export function list(
authWrapper: AuthWrapper,
location: Location,
delimiter?: string,
pageToken?: string,
maxResults?: number
): RequestInfo<ListResult> {
let urlParams = {};
if (location.isRoot) {
urlParams['prefix'] = '';
} else {
urlParams['prefix'] = location.path + '/';
}
if (delimiter && delimiter.length > 0) {
urlParams['delimiter'] = delimiter;
}
if (pageToken) {
urlParams['pageToken'] = pageToken;
}
if (maxResults) {
urlParams['maxResults'] = maxResults;
}
const urlPart = location.bucketOnlyServerUrl();
const url = UrlUtils.makeUrl(urlPart);
const method = 'GET';
const timeout = authWrapper.maxOperationRetryTime();
const requestInfo = new RequestInfo(
url,
method,
listHandler(authWrapper),
timeout
);
requestInfo.urlParams = urlParams;
requestInfo.errorHandler = sharedErrorHandler(location);
return requestInfo;
}

export function getDownloadUrl(
authWrapper: AuthWrapper,
location: Location,
Expand Down
4 changes: 4 additions & 0 deletions packages/storage/src/implementation/type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,10 @@ export function isString(p: any): boolean {
return typeof p === 'string' || p instanceof String;
}

export function isInteger(p: any): boolean {
return isNumber(p) && Number.isInteger(p);
}

export function isNumber(p: any): boolean {
return typeof p === 'number' || p instanceof Number;
}
Expand Down
31 changes: 31 additions & 0 deletions packages/storage/src/list.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/**
* @license
* Copyright 2019 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import { Reference } from './reference';

/**
* @fileoverview Documentation for ListOptions and ListResult format.
*/
export type ListOptions = {
maxResults?: number | null;
pageToken?: string | null;
};

export type ListResult = {
prefixes: Reference[];
items: Reference[];
nextPageToken?: string | null;
};
Loading