Thai  Son

Thai Son

1658824800

Cập Nhật Mục DynamoDB Với TypeScript

Ứng dụng của tôi có một bảng với người dùng và để cập nhật người dùng với một id nhất định, tôi có updateUserchức năng này. Tham số thứ hai nhận một đối tượng với các trường cho bản cập nhật.

export const updateUser = (id: string, params: Partial<User>) => {
  return documentClient
    .update({
      ...getUserItemParams(id),
      ...getUpdateParams(params),
    })
    .promise()
}

Để đơn giản hóa các tương tác với DynamoDB, tôi có một số người trợ giúp.

Hàm getUpdateParamsnhận một đối tượng với các trường và trả về UpdateExpression, ExpressionAttributeNamesExpressionAttributeValueschúng ta cần chuyển đối tượng này đến ứng dụng khách tài liệu để cập nhật mục.

export const getUpdateParams = (params: { [key: string]: any }) => ({
  UpdateExpression: `set ${Object.entries(params)
    .map(([key]) => `#${key} = :${key}, `)
    .reduce((acc, str) => acc + str)
    .slice(0, -2)}`,

  ExpressionAttributeNames: Object.keys(params).reduce(
    (acc, key) => ({
      ...acc,
      [`#${key}`]: key,
    }),
    {}
  ),

  ExpressionAttributeValues: Object.entries(params).reduce(
    (acc, [key, value]) => ({
      ...acc,
      [`:${key}`]: value,
    }),
    {}
  ),
})

Tôi có một chức năng giống như getUserItemParamscho mọi bảng. Nó trả về một đối tượng mà chúng ta cần lấy, cập nhật hoặc xóa một mục.

export const getUserItemParams = (id: string) => ({
  TableName: tableName.users,
  Key: { id },
})

Nguồn: https://radzion.com/blog/update-dynamodb

#dynamodb #typescript 

What is GEEK

Buddha Community

Cập Nhật Mục DynamoDB Với TypeScript
Thai  Son

Thai Son

1658824800

Cập Nhật Mục DynamoDB Với TypeScript

Ứng dụng của tôi có một bảng với người dùng và để cập nhật người dùng với một id nhất định, tôi có updateUserchức năng này. Tham số thứ hai nhận một đối tượng với các trường cho bản cập nhật.

export const updateUser = (id: string, params: Partial<User>) => {
  return documentClient
    .update({
      ...getUserItemParams(id),
      ...getUpdateParams(params),
    })
    .promise()
}

Để đơn giản hóa các tương tác với DynamoDB, tôi có một số người trợ giúp.

Hàm getUpdateParamsnhận một đối tượng với các trường và trả về UpdateExpression, ExpressionAttributeNamesExpressionAttributeValueschúng ta cần chuyển đối tượng này đến ứng dụng khách tài liệu để cập nhật mục.

export const getUpdateParams = (params: { [key: string]: any }) => ({
  UpdateExpression: `set ${Object.entries(params)
    .map(([key]) => `#${key} = :${key}, `)
    .reduce((acc, str) => acc + str)
    .slice(0, -2)}`,

  ExpressionAttributeNames: Object.keys(params).reduce(
    (acc, key) => ({
      ...acc,
      [`#${key}`]: key,
    }),
    {}
  ),

  ExpressionAttributeValues: Object.entries(params).reduce(
    (acc, [key, value]) => ({
      ...acc,
      [`:${key}`]: value,
    }),
    {}
  ),
})

Tôi có một chức năng giống như getUserItemParamscho mọi bảng. Nó trả về một đối tượng mà chúng ta cần lấy, cập nhật hoặc xóa một mục.

export const getUserItemParams = (id: string) => ({
  TableName: tableName.users,
  Key: { id },
})

Nguồn: https://radzion.com/blog/update-dynamodb

#dynamodb #typescript 

The Definitive Guide to TypeScript & Possibly The Best TypeScript Book

TypeScript Deep Dive

I've been looking at the issues that turn up commonly when people start using TypeScript. This is based on the lessons from Stack Overflow / DefinitelyTyped and general engagement with the TypeScript community. You can follow for updates and don't forget to ★ on GitHub 🌹

Reviews

  • Thanks for the wonderful book. Learned a lot from it. (link)
  • Its probably the Best TypeScript book out there. Good Job (link)
  • Love how precise and clear the examples and explanations are! (link)
  • For the low, low price of free, you get pages of pure awesomeness. Chock full of source code examples and clear, concise explanations, TypeScript Deep Dive will help you learn TypeScript development. (link)
  • Just a big thank you! Best TypeScript 2 detailed explanation! (link)
  • This gitbook got my project going pronto. Fluent easy read 5 stars. (link)
  • I recommend the online #typescript book by @basarat you'll love it.(link)
  • I've always found this by @basarat really helpful. (link)
  • We must highlight TypeScript Deep Dive, an open source book.(link)
  • Great online resource for learning. (link)
  • Thank you for putting this book together, and for all your hard work within the TypeScript community. (link)
  • TypeScript Deep Dive is one of the best technical texts I've read in a while. (link)
  • Thanks @basarat for the TypeScript Deep Dive Book. Help me a lot with my first TypeScript project. (link)
  • Thanks to @basarat for this great #typescript learning resource. (link)
  • Guyz excellent book on Typescript(@typescriptlang) by @basarat (link)
  • Leaning on the legendary @basarat's "TypeScript Deep Dive" book heavily at the moment (link)
  • numTimesPointedPeopleToBasaratsTypeScriptBook++; (link)
  • A book not only for typescript, a good one for deeper JavaScript knowledge as well. link
  • In my new job, we're using @typescriptlang, which I am new to. This is insanely helpful huge thanks, @basarat! link
  • Thank you for writing TypeScript Deep Dive. I have learned so much. link
  • Loving @basarat's @typescriptlang online book basarat.gitbooks.io/typescript/# loaded with great recipes! link
  • Microsoft doc is great already, but if want to "dig deeper" into TypeScript I find this book of great value link
  • Thanks, this is a great book 🤓🤓 link
  • Deep dive to typescript is awesome in so many levels. i find it very insightful. Thanks link
  • @basarat's intro to @typescriptlang is still one of the best going (if not THE best) link
  •  
  • This is sweet! So many #typescript goodies! link

Get Started

If you are here to read the book online get started.

Translations

Book is completely free so you can copy paste whatever you want without requiring permission. If you have a translation you want me to link here. Send a PR.

Other Options

You can also download one of the Epub, Mobi, or PDF formats from the actions tab by clicking on the latest build run. You will find the files in the artifacts section.

Special Thanks

All the amazing contributors 🌹

Share

Share URL: https://basarat.gitbook.io/typescript/

Author: Basarat
Source Code: https://github.com/basarat/typescript-book/ 
License: View license

#typescript #opensource 

A GUI for Local DynamoDB- Dynamodb-Admin

Quick Start Guide

1. Install the package globally from npm.

$ npm install -g dynamodb-admin

2. Run DynamoDB locally inside a Docker container

Make sure you have Docker installed on your system. Instructions are here.

Now pull and run the Docker dynamodb-local image to spin up your very own DynamoDB instance running on port 8000.

$ docker pull amazon/dynamodb-local
$ docker run -p 8000:8000 amazon/dynamodb-local

3. Start dynamodb-admin (with defaults)

MacOS/Linux

$ dynamodb-admin

Windows

> export DYNAMO_ENDPOINT=http://localhost:8000
> dynamodb-admin

After these steps you will have:

The next step is to create a table and start reading/writing to it!

Advanced Setup

You may need to override regions, endpoints and/or credentials to peek inside local DynamoDB instances you have spun up to replicate a production environment.

If so, just override the defaults when starting the service. You can override some, or all of these, as required.

DYNAMO_ENDPOINT=http://localhost:<PORT> AWS_REGION=<AWS-REGION> AWS_ACCESS_KEY_ID=<YOUR-ACCESS-KEY> AWS_SECRET_ACCESS_KEY=<YOUR-SECRET> dynamodb-admin

Setting up your Tables

The easy way — for simple use cases

Here we are going to create your table using the dynamodb-admin GUI. This is most likely going to be appropriate for your use-case.

Clicking on ‘Create table’ takes us to a screen where we can define how our table should look. Remember that DynamoDB is effectively a key-value store, meaning to get started we only need to define a table name and a hash attribute (the primary key). If you expect that you’ll need to perform lookups based on another attribute of your data, you may want to add some Secondary Indices.

In this example, I’ve named the table ‘Cats’ and given it a primary index ‘name’ and a secondary index ‘owner’. Both indices are of type String and we must give the secondary index a name — which can be different from the name of the attribute.

‘name’ is not a good choice of primary index in practice, as it means only one cat with a given name can be present in the table. Instead, it would be better to give each cat a unique id and use that as the primary index.

Finally, add your first item to the table by clicking the ‘Create item’ link on the top right. This will take you to a new screen where you can enter the json which defines the record. The only requirement for each entry is that the primary key is included.

The Hard(er) Way — for more complex table structures

Using the GUI to set up tables is fine for simple tables, or when you’re just exploring how your data storage might be structured. However, if you are trying to mimic a complex table, or you want to stand-up tables quickly for testing you may want to use the command line to create the table(s) for you.

1. Install the AWS CLI

Instructions for installing (for Mac) via the command line are here. This is a very powerful utility tool. I’d recommend installing it if you work with AWS even if you don’t opt to use it here.

2. Create a table schema

If you already have a table schema you can skip this and move along to Step 3.

$ aws dynamodb create-table --generate-cli-skeleton > dynamo_table_def.json

This will create a basic table schema and pipe it into a file named dynamo_table_def.json.

You can now open the json file and edit it to fit your desired table schema. This is great because you can now use this same schema file when you need the table, rather than manually setting it up each time via the GUI.

If you’re just curious what the schema should look like, or you need some inspiration for your own — here is the schema for the Cats table.

{
  "AttributeDefinitions": [
    {
      "AttributeName": "name",
      "AttributeType": "S"
    },
    {
      "AttributeName": "owner",
      "AttributeType": "S"
    }
  ],
  "TableName": "Cats",
  "KeySchema": [
    {
      "AttributeName": "name",
      "KeyType": "HASH"
    }
  ],
  "ProvisionedThroughput": {
    "ReadCapacityUnits": 3,
    "WriteCapacityUnits": 3
  },
  "GlobalSecondaryIndexes": [
    {
      "IndexName": "idx_owner",
      "KeySchema": [
        {
          "AttributeName": "owner",
          "KeyType": "HASH"
        }
      ],
      "Projection": {
        "ProjectionType": "ALL"
      },
      "ProvisionedThroughput": {
        "ReadCapacityUnits": 3,
        "WriteCapacityUnits": 3
      }
    }
  ]
}

3. Use the schema to create the table

Finally, create the table locally

$ aws dynamodb create-table --cli-input-json file://dynamo_table_def.json --endpoint-url http://localhost:8000

Remember the --endpoint-url parameter, otherwise a real table will be created in whatever region your AWS CLI defaults to.

After running this command, go back to dynamodb-admin in your browser. You’ll see your table has been created. Now it’s time to use it!

Use Cases

I’ve picked 3 examples to show how dynamodb-admin can help you develop and test your applications.

Running locally alongside an application

This example is super simple. Let’s say you’re developing a Python application which reads from a DynamoDB table of movies. You may want run a local DynamoDB instance for development and tests, to avoid standing up unnecessary infrastructure. Dynamodb-local is a godsend for this. However it can be fiddly to put data in the table, from the command line.

You could write code to put the correct items in the table. Indeed for tests this might be ideal, as you absolutely should test the logic you’re using to read and write from the table.

However to quickly test some code path or to build out a feature, when the remote infrastructure or data is not present, it’s typically much easier to put the data into the DynamoDB table manually.

You can set up your table and add some movies, using the GUI, as described above. Then read from the table like so:

from pprint import pprint
import boto3
from botocore.exceptions import ClientError


def get_movie(title, year, dynamodb=None):
    if not dynamodb:
        dynamodb = boto3.resource('dynamodb', endpoint_url="http://localhost:8000")

    table = dynamodb.Table('Movies')

    try:
        response = table.get_item(Key={'year': year, 'title': title})
    except ClientError as e:
        print(e.response['Error']['Message'])
    else:
        return response['Item']


if __name__ == '__main__':
    movie = get_movie("The Big New Movie", 2015,)
    if movie:
        print("Get movie succeeded:")
        pprint(movie, sort_dicts=False)

Creating the table and putting items in it, using dynamodb-admin, lets you focus on the business logic. When you’re happy with how your logic looks, you can focus on writing to the table.

Using dynamodb-admin as a library

Since dynamodb-admin is a Node library, we can use it inside our Node projects. This is again great for local development, as each time you run the service you have what is effectively the AWS console ready to view and manipulate the data.

const AWS = require('aws-sdk');
const {createServer} = require('dynamodb-admin');
 
const dynamodb = new AWS.DynamoDB();
const dynClient = new AWS.DynamoDB.DocumentClient({service: dynamodb});
 
const app = createServer(dynamodb, dynClient);
 
const port = 8001;
const server = app.listen(port);
server.on('listening', () => {
  const address = server.address();
  console.log(`  listening on http://0.0.0.0:${address.port}`);
});

Using dynamodb-admin with AWS Amplify

AWS Amplify is a development framework that deals with a lot of the common problems when building a mobile or web application, setting up the infrastructure required for you. Each part of the framework deserves a blog post of its own, but here we are going to be looking at mocking the DynamoDB tables Amplify creates based on your GraphQL API definition.

If you’d like to find out how to use Amplify to create a GraphQL API the documentation is here

Amplify let’s you mock services used by your app with the Amplify CLI tool by running

$ amplify mock <service>

If you have used Amplify to create a GraphQL API to serve as the backend for your project you can run

$ amplify mock api

This will do two things:

  1. Starts a mock Appsync API endpoint on port 20002
  2. Creates a DynamoDB instance on port 62224

We can now use dynamodb-admin to take a peek inside the tables Amplify has created, based on our API’s requirements by running

$ AWS_REGION=us-fake-1 AWS_ACCESS_KEY_ID=fake AWS_SECRET_ACCESS_KEY=fake DYNAMO_ENDPOINT=http://localhost:62224  dynamodb-admin

I’ve personally found this really useful to test locally, before committing to pushing my API changes.

Originally published by https://medium.com/swlh 

#dynamodb #aws #code #dynamodb-admin #dynamodb-local

Update DynamoDB Item with TypeScript

My app has a table with users, and to update a user with a given id, I have the updateUser function. The second parameter takes an object with fields for the update.

export const updateUser = (id: string, params: Partial<User>) => {
  return documentClient
    .update({
      ...getUserItemParams(id),
      ...getUpdateParams(params),
    })
    .promise()
}

 

See more at: https://radzion.com/blog/update-dynamodb

#dynamodb #typescript 

Atualizar Item Do DynamoDB Com TypeScript

Meu aplicativo tem uma tabela com usuários, e para atualizar um usuário com um determinado id, tenho a updateUserfunção. O segundo parâmetro pega um objeto com campos para atualização.

export const updateUser = (id: string, params: Partial<User>) => {
  return documentClient
    .update({
      ...getUserItemParams(id),
      ...getUpdateParams(params),
    })
    .promise()
}

Para simplificar as interações com o DynamoDB, tenho vários auxiliares.

A getUpdateParamsfunção pega um objeto com campos e retorna UpdateExpression, ExpressionAttributeNames, e ExpressionAttributeValues, que precisamos passar para o cliente do documento para atualizar o item.

export const getUpdateParams = (params: { [key: string]: any }) => ({
  UpdateExpression: `set ${Object.entries(params)
    .map(([key]) => `#${key} = :${key}, `)
    .reduce((acc, str) => acc + str)
    .slice(0, -2)}`,

  ExpressionAttributeNames: Object.keys(params).reduce(
    (acc, key) => ({
      ...acc,
      [`#${key}`]: key,
    }),
    {}
  ),

  ExpressionAttributeValues: Object.entries(params).reduce(
    (acc, [key, value]) => ({
      ...acc,
      [`:${key}`]: value,
    }),
    {}
  ),
})

Eu tenho uma função como getUserItemParamspara cada tabela. Ele retorna um objeto que precisamos para obter, atualizar ou excluir um item.

export const getUserItemParams = (id: string) => ({
  TableName: tableName.users,
  Key: { id },
})

Fonte: https://radzion.com/blog/update-dynamodb

#dynamodb #typescript