Note aws-amplify 5 has been released. If you are looking for upgrade guidance click here
AWS Amplify provides a declarative and easy-to-use interface across different categories of cloud operations. AWS Amplify goes well with any JavaScript based frontend workflow and React Native for mobile developers.
Our default implementation works with Amazon Web Services (AWS), but AWS Amplify is designed to be open and pluggable for any custom backend or service.
Category | AWS Provider | Description |
---|---|---|
Authentication | Amazon Cognito | APIs and Building blocks to create Authentication experiences. |
Analytics | Amazon Pinpoint | Collect Analytics data for your application including tracking user sessions. |
REST API | Amazon API Gateway | Sigv4 signing and AWS auth for API Gateway and other REST endpoints. |
GraphQL API | AWS AppSync | Interact with your GraphQL or AWS AppSync endpoint(s). |
DataStore | AWS AppSync | Programming model for shared and distributed data, with simple online/offline synchronization. |
Storage | Amazon S3 | Manages content in public, protected, private storage buckets. |
Geo (Developer preview) | Amazon Location Service | Provides APIs and UI components for maps and location search for JavaScript-based web apps. |
Push Notifications | Amazon Pinpoint | Allows you to integrate push notifications in your app with Amazon Pinpoint targeting and campaign management support. |
Interactions | Amazon Lex | Create conversational bots powered by deep learning technologies. |
PubSub | AWS IoT | Provides connectivity with cloud-based message-oriented middleware. |
Internationalization | --- | A lightweight internationalization solution. |
Cache | --- | Provides a generic LRU cache for JavaScript developers to store data with priority and expiration settings. |
Predictions | Various* | Connect your app with machine learning services like NLP, computer vision, TTS, and more. |
AWS Amplify is available as aws-amplify
on npm.
To get started pick your platform from our Getting Started home page
If you are using default exports from any Amplify package, then you will need to migrate to using named exports. For example:
- import Amplify from 'aws-amplify';
+ import { Amplify } from 'aws-amplify'
- import Analytics from '@aws-amplify/analytics';
+ import { Analytics } from '@aws-amplify/analytics';
// or better
+ import { Analytics } from 'aws-amplify';
- import Storage from '@aws-amplify/storage';
+ import { Storage } from '@aws-amplify/storage';
// or better
+ import { Storage } from 'aws-amplify';
Datastore predicate syntax has changed, impacting the DataStore.query
, DataStore.save
, DataStore.delete
, and DataStore.observe
interfaces. For example:
- await DataStore.delete(Post, (post) => post.status('eq', PostStatus.INACTIVE));
+ await DataStore.delete(Post, (post) => post.status.eq(PostStatus.INACTIVE));
- await DataStore.query(Post, p => p.and( p => [p.title('eq', 'Amplify Getting Started Guide'), p.score('gt', 8)]));
+ await DataStore.query(Post, p => p.and( p => [p.title.eq('Amplify Getting Started Guide'), p.score.gt(8)]));
npm install -g @aws-amplify/cli
amplify codegen models
Storage.list
has changed the name of the maxKeys
parameter to pageSize
and has a new return type that contains the results list. For example:
- const photos = await Storage.list('photos/', { maxKeys: 100 });
- const { key } = photos[0];
+ const photos = await Storage.list('photos/', { pageSize: 100 });
+ const { key } = photos.results[0];
Storage.put
with resumable turned on has changed the key to no longer include the bucket name. For example:
- let uploadedObjectKey;
- Storage.put(file.name, file, {
- resumable: true,
- // Necessary to parse the bucket name out to work with the key
- completeCallback: (obj) => uploadedObjectKey = obj.key.substring( obj.key.indexOf("/") + 1 )
- }
+ let uploadedObjectKey;
+ Storage.put(file.name, file, {
+ resumable: true,
+ completeCallback: (obj) => uploadedObjectKey = obj.key
+ }
Analytics.record
no longer accepts string as input. For example:
- Analytics.record('my example event');
+ Analytics.record({ name: 'my example event' });
The JS
export has been removed from @aws-amplify/core
in favor of exporting the functions it contained.
Any calls to Amplify.Auth
, Amplify.Cache
, and Amplify.ServiceWorker
are no longer supported. Instead, your code should use the named exports. For example:
- import { Amplify } from 'aws-amplify';
- Amplify.configure(...);
- // ...
- Amplify.Auth.signIn(...);
+ import { Amplify, Auth } from 'aws-amplify';
+ Amplify.configure(...);
+ // ...
+ Auth.signIn(...);
@react-native-community/netinfo
@react-native-async-storage/async-storage
// React Native
yarn add aws-amplify amazon-cognito-identity-js @react-native-community/netinfo @react-native-async-storage/async-storage
npx pod-install
// Expo
yarn add aws-amplify @react-native-community/netinfo @react-native-async-storage/async-storage
AWS.credentials
and AWS.config
don’t exist anymore in Amplify JavaScript.aws-sdk@2.x
has been removed from Amplify@3.x.x
in favor of version 3 of aws-sdk-js. We recommend to migrate to aws-sdk-js-v3 if you rely on AWS services that are not supported by Amplify, since aws-sdk-js-v3 is imported modularly.If you can't migrate to aws-sdk-js-v3 or rely on aws-sdk@2.x, you will need to import it separately.
If you are using exported paths within your Amplify JS application, (e.g. import from "@aws-amplify/analytics/lib/Analytics"
) this will now break and no longer will be supported. You will need to change to named imports:
import { Analytics } from 'aws-amplify';
If you are using categories as Amplify.<Category>
, this will no longer work and we recommend to import the category you are needing to use:
import { Auth } from 'aws-amplify';
For more information on contributing to DataStore / how DataStore works, see the DataStore Docs
Compatible type for S3 streaming body exposed via Amplify public interfaces, like GetObjectCommandOutput exposed via download API. It's also compatible with the custom transfer handler interface HttpResponse.body.
Accepts an array of arrays with exactly 1 or 2 values and translates those arrays to "item" or "item1/item2" strings on the custom user agent
Basic option type for endpoint resolvers. It contains region only.
parse errors from given response. If no error code is found, return undefined. This function is protocol-specific (e.g. JSON, XML, etc.)
The package name of the app that's recording the event.
The title of the app that's recording the event.
The version number of the app that's recording the event.
One or more custom attributes that are associated with the event.
The version of the SDK that's running on the client device.
The name of the event.
One or more custom metrics that are associated with the event.
The name of the SDK that's being used to record the event.
Information about the session in which the event occurred.
The date and time, in ISO 8601 format, when the event occurred.
GraphQLSource or string, the type of the parameter for calling graphql.parse
Use basic Record interface to workaround fetch Header class not available in Node.js
The header names must be lowercased.
TODO: use LowerCase
Type to infer the option type of a transfer handler type.
Completely internal to BackgroundProcessManager
, and describes the structure of
an entry in the jobs registry.
An object provided by the caller that can be used to identify the description
of the job, which can otherwise be unclear from the promise
and
terminate
function. The description
can be a string. (May be extended
later to also support object refs.)
Useful for troubleshooting why a manager is waiting for long periods of time
on close()
.
The underlying promise provided by the job function to wait for.
Request the termination of the job.
Type to intersect multiple types if they have no conflict keys.
A slimmed down version of the AWS SDK v3 middleware, only handling tasks after Serde.
The context object to store states across the middleware chain.
The number of times the request has been attempted. This is set by retry middleware
A slimmed down version of the AWS SDK v3 middleware handler, only handling instantiated requests
Constructs a model and records it with its metadata in a weakset. Allows for the separate storage of core model fields and Amplify/DataStore metadata fields that the customer app does not want exposed.
A function that accepts a ModelPrecicate
This is used as predicates in DataStore.save()
, DataStore.delete()
, and
DataStore sync expressions.
DataStore.save(record, model => model.field.eq('some value'))
Logical operators are supported. But, condtiions are related records are NOT supported. E.g.,
DataStore.delete(record, model => model.or(m => [
m.field.eq('whatever'),
m.field.eq('whatever else')
]))
Type to convert a middleware option type to a middleware type with the given option type.
Utility type for checking if the generic type is a provider or a Record that has the key 'provider'. If it's a provider, check if it's the S3 Provider, use the default type else use the generic's 'get' method return type. If it's a Record, check if provider is 'AWSS3', use the default type else use any.
Provides information about endpoints and the events that they're associated with.
Reference: S3ProviderPutConfig
A function that accepts a RecursiveModelPrecicate
This is used in DataStore.query()
, DataStore.observe()
, and
DataStore.observeQuery()
as the second argument. E.g.,
DataStore.query(MyModel, model => model.field.eq('some value'))
More complex queries should also be supported. E.g.,
DataStore.query(MyModel, model => model.and(m => [
m.relatedEntity.or(relative => [
relative.relativeField.eq('whatever'),
relative.relativeField.eq('whatever else')
]),
m.myModelField.ne('something')
]))
Reduce the API surface of Fetch API's Body mixin to only the methods we need. In React Native, body.arrayBuffer() is not supported. body.formData() is not supported for now.
Options for endpoint resolver.
Configuration options for the S3 copy function.
Configuration options for the S3 put function.
Explicitly defined fields plus implied fields. (E.g., foreign keys.)
Explicitly defined fields.
If provider is AWSS3, provider doesn't have to be specified since it's the default, else it has to be passed into config.
Utility type to allow custom provider to use any config keys, if provider is set to AWSS3 then it should use AWSS3Provider's config.
Time in milleseconds to wait for GQL_CONNECTION_INIT message
Default Time in milleseconds to alert for missed GQL_CONNECTION_KEEP_ALIVE message
Default Time in milleseconds to wait for GQL_CONNECTION_KEEP_ALIVE message
Used by the Async Storage Adapter to concatenate key values
for a record. For instance, if a model has the following keys:
customId: ID! @primaryKey(sortKeyFields: ["createdAt"])
,
we concatenate the customId
and createdAt
as:
12-234-5#2022-09-28T00:00:00.000Z
Date & time utility functions to abstract the aws-sdk
away from users.
(v2 => v3 modularization is a breaking change)
Used for generating spinal-cased index name from an array of
key field names.
E.g. for keys [id, title]
=> 'id-title'
The point after which queries composed of multiple simple OR conditions should scan-and-filter instead of individual queries for each condition.
At some point, this should be configurable and/or dynamic based on table size and possibly even on observed average seek latency. For now, it's based on an manual "binary search" for the breakpoint as measured in the unit test suite. This isn't necessarily optimal. But, it's at least derived empirically, rather than theoretically and without any verification!
REMEMBER! If you run more realistic benchmarks and update this value, update this comment so the validity and accuracy of future query tuning exercises can be compared to the methods used to derive the current value. E.g.,
etc...
Default delay time in milleseconds between when reconnect is triggered vs when it is attempted
Default interval time in milleseconds between when reconnect is re-attempted
The service name used to sign requests if the API requires authentication. The service name used to sign requests if the API requires authentication. The service name used to sign requests if the API requires authentication.
Time in milleseconds to wait for GQL_START_ACK message
Each identifier type is represented using nominal types, see: https://basarat.gitbook.io/typescript/main-1/nominaltyping
Configure & register Storage singleton instance.
Tells us which data source a model is attached to (lazy loads from).
If Deatched
, the model's lazy properties will only ever return properties
from memory provided at construction time.
A Cognito Identity-specific transfer handler that does NOT sign requests, and disables caching.
The valid comparison operators that can be used as keys in a predicate comparison object.
Small utility function to generate a monotonically increasing ID. Used by GroupCondition to help keep track of which group is doing what, when, and where during troubleshooting.
The valid logical grouping keys for a predicate group.
This Symbol is used to reference an internal-only PubSub provider that is used for AppSync/GraphQL subscriptions in the API category.
Records the patches (as if against an empty object) used to initialize an instance of a Model. This can be used for determining which fields to send to the cloud durnig a CREATE mutation.
Collection of instantiated models to allow storage of metadata apart from the model visible to the consuming app -- in case the app doesn't have metadata fields (_version, _deleted, etc.) exposed on the model itself.
Maps a model to its related models for memoization/immutability.
Stores data for crafting the correct update mutation input for a model.
Patch[]
- array of changed fields and metadata.PersistentModel
- the source model, used for diffing object-type fields.A map from keys (exposed to customers) to the internal predicate data structures invoking code should not muck with.
S3 transfer handler for browser and React Native based on XHR. On top of basic transfer handler, it also supports x-amz-content-sha256 header, and request&response process tracking. S3 transfer handler for node based on Node-fetch. On top of basic transfer handler, it also supports x-amz-content-sha256 header. However, it does not support request&response process tracking like browser.
provide an object as the in-memory cache
An aysnc
implementation of Array.every()
. Returns as soon as a non-match is found.
The items to check.
The async matcher function, expected to
return Promisetrue
for a matching item, false
otherwise.
A Promise<boolean>
, true
if every item matches; false
otherwise.
An async
implementation of Array.filter()
. Returns after all items have been filtered.
TODO: Return AsyncIterable.
The items to filter.
The async
matcher function, expected to
return Promisetrue
for a matching item, false
otherwise.
A Promise<T>
of matching items.
An aysnc
implementation of Array.some()
. Returns as soon as a match is found.
The items to check.
The async matcher function, expected to
return Promisetrue
for a matching item, false
otherwise.
A Promise<boolean>
, true
if "some" items match; false
otherwise.
Registers a model instance against a data source (DataStore, API, or Detached/None).
The API option is demonstrative. Lazy loading against API is not yet implemented.
A model instance or array of instances
A ModelAttachment data source
passes the result
back through after attachment
Converts blob to array buffer
Creates a predicate without any conditions that can be passed to customer code to have conditions added to it.
For example, in this query:
await DataStore.query(
Model,
item => item.field.eq('value')
);
buildSeedPredicate(Model)
is used to create item
, which is passed to the
predicate function, which in turn uses that "seed" predicate (item
) to build
a predicate tree.
The model the predicate will query.
If the given (operator, operand) indicate the need for a special NULL
comparison,
that WHERE
clause condition will be returned. If not special NULL
handling is
needed, null
will be returned, and the caller should construct the WHERE
clause component using the normal operator map(s) and parameterization.
"beginsWith" | "contains" | "notContains" | "between" | "eq" | "ne" | "le" | "lt" | "ge" | "gt"
any
(string | null) The WHERE
clause component or null
if N/A.
Organizes blocks from Rekognition API to each of the categories and and structures their data accordingly.
Organizes blocks from Textract API to each of the categories and and structures their data accordingly.
Throws an exception if the schema is using a codegen version that is not supported.
Set the supported version by setting majorVersion and minorVersion This functions similar to ^ version range. The tested codegenVersion major version must exactly match the set majorVersion The tested codegenVersion minor version must be gt or equal to the set minorVersion Example: For a min supported version of 5.4.0 set majorVersion = 5 and minorVersion = 4
This regex will not work when setting a supported range with minor version of 2 or more digits. i.e. minorVersion = 10 will not work The regex will work for testing a codegenVersion with multi digit minor versions as long as the minimum minorVersion is single digit. i.e. codegenVersion = 5.30.1, majorVersion = 5, minorVersion = 4 PASSES
schema codegenVersion
Throws an exception if the schema has not been initialized
by initSchema()
.
To be called before trying to access schema.
Currently this only needs to be called in start()
and clear()
because
all other functions will call start first.
Queries the DataStore metadata tables to see if they are the expected version. If not, clobbers the whole DB. If so, leaves them alone. Otherwise, simply writes the schema version.
SIDE EFFECT:
Storage adapter containing the metadata.
The expected schema version.
Gets the closest parent element that matches the passed selector.
The element whose parents to check.
The CSS selector to match against.
True if the selector should test against the passed element itself.
The matching element or undefined.
Compose a transfer handler with a core transfer handler and a list of middleware.
Core transfer handler
List of middleware
A transfer handler whose option type is the union of the core transfer handler's option type and the middleware's option type.
A middleware that adds the x-amz-content-sha256 header to the request if it is not already present. It's required for S3 requests in browsers where the request body is sent in 1 chunk.
Convert xhr.getAllResponseHeaders() string to a Record<string, string>. Note that modern browser already returns header names in lowercase.
string of headers returned from xhr.getAllResponseHeaders()
selective sync predicate group
the total number of OR'd predicates in the filter group
Delegates the handling of events for an element matching a selector to an ancestor of the matching element.
The ancestor element to add the listener to.
The event type to listen to.
A CSS selector to match against child elements.
A function to run any time the event happens.
A configuration options object. The available options:
- useCapture
The delegate object. It contains a destroy method.
Deserializes a string to a boolean. Returns undefined if input is undefined. Returns true if input is 'true', otherwise false.
Deserializes a string to a number. Returns undefined if input is undefined.
Deserializes a string to a Date. Returns undefined if input is undefined. It supports epoch timestamp; rfc3339(cannot have a UTC, fractional precision supported); rfc7231(section 7.1.1.1)
A Cognito Identity-specific middleware that disables caching for all requests.
Dispatches an event on the passed element.
The DOM element to dispatch the event on.
The type of event to dispatch.
The return value of element.dispatchEvent
, which will
be false if any of the event listeners called preventDefault
.
set of field names used with dynamic auth modes configured for the provided model definition
Function that makes sure the deserializer receives non-empty array.
The endpoint resolver function that returns the endpoint URL for a given region. The endpoint resolver function that returns the endpoint URL for a given region. The endpoint resolver function that returns the endpoint URL for a given region, and input parameters.
The endpoint resolver function that returns the endpoint URL for a given region. The endpoint resolver function that returns the endpoint URL for a given region. The endpoint resolver function that returns the endpoint URL for a given region, and input parameters.
The endpoint resolver function that returns the endpoint URL for a given region. The endpoint resolver function that returns the endpoint URL for a given region. The endpoint resolver function that returns the endpoint URL for a given region, and input parameters.
Wraps encodeURIComponent to encode additional characters to fully adhere to RFC 3986.
URI string to encode
RFC 3986 encoded string
Backwards-compatability for schema generated prior to custom primary key support:
the single field targetName
has been replaced with an array of targetNames
.
targetName
and targetNames
are exclusive (will never exist on the same schema)
array of targetNames, or undefined
selective sync predicate group
set of distinct field names in the filter group
Determines what source a model instance should lazy load from.
If the instace was never explicitly registered, it is detached by default.
A model instance
Gets all attributes of an element as a plain JavaScriot object.
The element whose attributes to get.
An object whose keys are the attribute keys and whose values are the attribute values. If no attributes exist, an empty object is returned.
return the byte size of the string
Returns canonical headers.
Headers from the request.
Request headers that will be signed, and their values, separated by newline characters. Header names must use lowercase characters, must appear in alphabetical order, and must be followed by a colon (:). For the values, trim any leading or trailing spaces, convert sequential spaces to a single space, and separate the values for a multi-value header using commas.
Returns a canonical query string.
searchParams
from the request url.
URL-encoded query string parameters, separated by ampersands (&). Percent-encode reserved characters, including the space character. Encode names and values separately. If there are empty parameters, append the equals sign to the parameter name before encoding. After encoding, sort the parameters alphabetically by key name. If there is no query string, use an empty string ("").
Returns a canonical request.
Whether to uri encode the path as part of canonical uri. It's used for S3 only where the pathname is already uri encoded, and the signing process is not expected to uri encode it again. Defaults to true.
String created by by concatenating the following strings, separated by newline characters:
Returns a canonical uri.
pathname
from request url.
Whether to uri encode the path as part of canonical uri. It's used for S3 only where the pathname is already uri encoded, and the signing process is not expected to uri encode it again. Defaults to true.
URI-encoded version of the absolute path component URL (everything between the host and the question mark character (?) that starts the query string parameters). If the absolute path is empty, a forward slash character (/).
Returns the credential scope which restricts the resulting signature to the specified region and service.
Current date in the format 'YYYYMMDD'.
AWS region in which the service resides.
Service to which the signed request is being sent.
A string representing the credential scope with format 'YYYYMMDD/region/service/aws4_request'.
get current time
Get the AWS Services endpoint URL's DNS suffix for a given region. A typical AWS regional service endpoint URL will
follow this pattern: {endpointPrefix}.{region}.{dnsSuffix}. For example, the endpoint URL for Cognito Identity in
us-east-1 will be cognito-identity.us-east-1.amazonaws.com. Here the DnsSuffix is amazonaws.com
.
The DNS suffix
Returns expected date strings to be used in signing.
JavaScript Date
object.
FormattedDates
object containing the following:
Returns the hashed data a Uint8Array
.
SourceData
to be used as hashing key.
Hashable SourceData
.
Uint8Array
created from the data as input to a hash function.
Returns the hashed data as a hex string.
SourceData
to be used as hashing key.
Hashable SourceData
.
String using lowercase hexadecimal characters created from the data as input to a hash function.
Returns the hashed payload.
body
(payload) from the request.
String created using the payload in the body of the HTTP request as input to a hash function. This string uses lowercase hexadecimal characters. If the payload is empty, return precalculated result of an empty hash.
Explicitly defined fields plus implied fields. (E.g., foreign keys.)
Explicitly defined fields.
Uses performance.now() if available, otherwise, uses Date.now() (e.g. react native without a polyfill)
The values returned by performance.now() always increase at a constant rate, independent of the system clock (which might be adjusted manually or skewed by software like NTP).
Otherwise, performance.timing.navigationStart + performance.now() will be approximately equal to Date.now()
See: https://developer.mozilla.org/en-US/docs/Web/API/Performance/now#Example
Get a presigned URL for the getObject
API.
Get retry decider function
Function to load JavaScript error from HTTP response
Calculates and returns an AWS API Signature. https://docs.aws.amazon.com/IAM/latest/UserGuide/create-signed-request.html
HttpRequest
to be signed.
AWS API Signature to sign a request or url with.
Returns signed headers.
headers
from the request.
List of headers included in canonical headers, separated by semicolons (;). This indicates which headers are part of the signing process. Header names must use lowercase characters and must appear in alphabetical order.
Returns a signing key to be used for signing requests.
AWS secret access key from credentials.
Current date in the format 'YYYYMMDD'.
AWS region in which the service resides.
Service to which the signed request is being sent.
Uint8Array
calculated from its composite parts.
Extracts common values used for signing both requests and urls.
Common SigningValues
used for signing.
Returns a Date
that is corrected for clock skew.
The offset of the system clock in milliseconds.
Date
representing the current time adjusted by the system clock offset.
Returns a string to be signed.
Current date in the format 'YYYYMMDDThhmmssZ'.
String representing the credential scope with format 'YYYYMMDD/region/service/aws4_request'.
Hashed canonical request.
A string created by by concatenating the following strings, separated by newline characters:
Determine what the managed timestamp field names are for the given model definition and return the mapping.
All timestamp fields are included in the mapping, regardless of whether the final field
names are the defaults or customized in the @model
directive.
modelDefinition to inspect.
An object mapping createdAt
and updatedAt
to their field names.
Returns the difference between clock time and the current system time if clock is skewed.
Clock time in milliseconds.
Current system clock offset in milliseconds.
Recursively parses object and populates value is node from "#text" key if it's available
Statelessly extracts the specified page from an array.
The source array to extract a page from.
A definition of the page to extract.
This items from records
matching the pagination
definition.
Attempts to apply type-aware, casted field values from a given init
object to the given draft
.
The initialization object to extract field values from.
The definition describing the target object shape.
The draft to apply field values to.
Takes a key object from registerPredicateInternals()
to fetch an internal
GroupCondition
object, which can then be used to query storage or
test/match objects.
This indirection exists to hide GroupCondition
from public interfaces, since
GroupCondition
contains extra methods and properties that public callers
should not use.
A key object previously returned by registerPredicateInternals()
Given an error code, returns true if it is related to a clock skew error.
String representation of some error.
True if given error is present in CLOCK_SKEW_ERROR_CODES
, false otherwise.
Checks if the provided date is within the skew window of 5 minutes.
Time to check for skew in milliseconds.
Offset to check clock against in milliseconds.
True if skewed. False otherwise.
Determines whether an object is a GraphQL style predicate comparison node, which must be an object containing a single "comparison operator" key, which then contains the operand or operands to compare against.
The object to test.
Determines whether a given string is DNS compliant per the rules outlined by S3. Length, capitaization, and leading dot restrictions are enforced by the DOMAIN_PATTERN regular expression.
Determines whether an object is a GraphQL style predicate "group", which must be an object containing a single "group key", which then contains the child condition(s).
E.g.,
{ and: [ ... ] }
{ not: { ... } }
The object to test.
check if passed value is an integer
Whether the browser's implementation of IndexedDB breaks on array lookups against composite indexes whose keypath contains a single column.
E.g., Whether store.createIndex(indexName, ['id'])
followed by
store.index(indexName).get([1])
will ever return records.
In all known, modern Safari browsers as of Q4 2022, the query against an index like
this will always return undefined
. So, the index needs to be created as a scalar.
Return true if the object is a strict object which means it's not Array, Function, Number, String, Boolean or Null
the Object
A light check to determine whether an object is a valid GraphQL Condition AST.
The object to test.
Determines whether the given object is a Model Constructor that DataStore can safely use to construct objects and discover related metadata.
The object to test.
A function that persists the s3 configs, so we don't need to assign each config parameter for every s3 API call.
Changes object keys to camel case. If optional parameter keys
is given, then we extract only the
keys specified in keys
.
Given an array of object, call makeCamelCase(...) on each option.
Maps an object to a new object using the provided instructions. The instructions are a map of the returning mapped object's property names to a single instruction of how to map the value from the original object to the new object. There are two types of instructions:
A string representing the property name of the original object to map to the new object. The value mapped from the original object will be the same as the value in the new object, and it can ONLY be string.
An array of two elements. The first element is the property name of the original object to map to the new object. The second element is a function that takes the value from the original object and returns the value to be mapped to the new object. The function can return any type.
Example:
const input = {
Foo: 'foo',
BarList: [{value: 'bar1'}, {value: 'bar2'}]
}
const output = map(input, {
someFoo: 'Foo',
bar: ['BarList', (barList) => barList.map(bar => bar.value)]
baz: 'Baz' // Baz does not exist in input, so it will not be in the output.
});
// output = { someFoo: 'foo', bar: ['bar1', 'bar2'] }
The object containing the data to compose mapped object.
The instructions mapping the object values to the new object.
A new object with the mapped values.
Tests if a DOM elements matches any of the test DOM elements or selectors.
The DOM element to test.
A DOM element, a CSS selector, or an array of DOM elements or CSS selectors to match against.
True of any part of the test matches.
Tests whether a DOM element matches a selector. This polyfills the native Element.prototype.matches method across browsers.
The DOM element to test.
The CSS selector to test element against.
True if the selector matches.
merge two sets of patches created by immer produce. newPatches take precedent over oldPatches for patches modifying the same path. In the case many consecutive pathces are merged the original model should always be the root model.
Example: A -> B, patches1 B -> C, patches2
mergePatches(A, patches1, patches2) to get patches for A -> C
the original Model the patches should be applied to
immer produce patch list
immer produce patch list (will take precedence)
merged patches
Returns an array of auth modes to try based on the schema, model, and
authenticated user (or lack thereof). Rules are sourced from getAuthRules
and returned in the order they ought to be attempted.
A sorted array of auth modes to attempt.
Updates a draft to standardize its customer-defined fields so that they are consistent with the data as it would look after having been synchronized from Cloud storage.
The exceptions to this are:
null
until set by cloud storage.This function should be expanded if/when deviations between canonical Cloud storage data and locally managed data are found. For now, the known areas that require normalization are:
undefined
-> null
.)Definition for the draft. Used to discover all fields.
The instance draft to apply normalizations to.
Returns an array of a DOM element's parent elements.
An array of all parent elemets, or an empty array if no parent elements are found.
Parse JSON response body to JavaScript object.
Error parser for AWS JSON protocol.
Parses the given url and returns an object mimicing a Location
object.
An object with the same properties as a Location
.
Parse CompleteMultipartUpload API response payload, which may be empty or error indicating internal server error, even when the status code is 200.
Predicate Group
GQL Filter Expression from Predicate Group
Given a Presignable
object, returns a Signature Version 4 presigned URL
object.
A URL
with authentication query params which can grant temporary access to AWS resources.
Creates a "seed" predicate that can be used to build an executable condition.
This is used in query()
, for example, to seed customer- E.g.,
const p = predicateFor({builder: modelConstructor, schema: modelSchema, pkField: string[]});
p.and(child => [
child.field.eq('whatever'),
child.childModel.childField.eq('whatever else'),
child.childModel.or(child => [
child.otherField.contains('x'),
child.otherField.contains('y'),
child.otherField.contains('z'),
])
])
predicateFor()
returns objecst with recursive getters. To facilitate this,
a query
and tail
can be provided to "accumulate" nested conditions.
The ModelMeta used to build child properties.
Scopes the query branch to a field.
A base query to build on. Omit to start a new query.
The point in an existing query
to attach new conditions to.
A ModelPredicate (builder) that customers can create queries with. (As shown in function description.)
Creates a link between a key (and generates a key if needed) and an internal
GroupCondition
, which allows us to return a key object instead of the gory
conditions details to customers/invoking code.
The internal condition to keep hidden.
The object DataStore will use to find the internal condition. If no key is given, an empty one is created.
selective sync predicate group
name of repeated field | null
Retry middleware
Serailize the parameters for configuring the S3 object. Currently used by
putObject
and createMultipartUpload
API.
Serialize the object key to a URL pathname.
Given a HttpRequest
, returns a Signature Version 4 signed HttpRequest
.
HttpRequest
to be signed.
A HttpRequest
with authentication headers which can grant temporary access to AWS resources.
Middleware that SigV4 signs request with AWS credentials, and correct system clock offset. This middleware is expected to be placed after retry middleware.
transfer the first letter of the keys to lowercase
the object need to be transferred
whitelist itself from being transferred
whitelist its children keys from being transferred
transfer the first letter of the keys to lowercase
the object need to be transferred
whitelist itself from being transferred
whitelist its children keys from being transferred
Get the first error reason of an observable. Allows for error maps to be easily applied to observable errors
an error from ZenObservable subscribe error callback
Middleware injects user agent string to specified header(default to 'x-amz-user-agent'), if the header is not set already.
TODO: incorporate new user agent design
Cache the payload of a response body. It allows multiple calls to the body, for example, when reading the body in both retry decider and error deserializer. Caching body is allowed here because we call the body accessor(blob(), json(), etc.) when body is small or streaming implementation is not available(RN).
Base transfer handler implementation using XMLHttpRequest to support upload and download progress events.
The request object.
The request options.
A promise that will be resolved with the response object.
Milliseconds to offset the date to compensate for clock skew between device & services
Clock offset in milliseconds
Clock offset in milliseconds
Default cache config
Default partition for AWS services. This is used when the region is not provided or the region is not recognized.
Maps operators to negated operators. Used to facilitate propagation of negation down a tree of conditions.
Pure JS XML parser that can be used in Non-browser environments, like React Native and Node.js. This is the same
XML parser implementation as used in AWS SDK S3 client. It depends on pure JavaScript XML parser library
fast-xml-parser
.
Drop-in replacement for fast-xml-parser's XmlParser class used in the AWS SDK S3 client XML deserializer. This
implementation is not tested against the full xml conformance test suite. It is only tested against the XML responses
from S3. This implementation requires the DOMParser
class in the runtime.
This data is adapted from the partition file from AWS SDK shared utilities but remove some contents for bundle size
concern. Information removed are dualStackDnsSuffix
, supportDualStack
, supportFIPS
, restricted partitions, and
list of regions for each partition other than global regions.