TECH |
Techable(テッカブル) |
VTuber事務所「FIRST STAGE PRODUCTION」始動!所属ライバーを紹介 |
https://techable.jp/archives/200665
|
firststageproduction |
2023-03-26 06:00:29 |
python |
Pythonタグが付けられた新着投稿 - Qiita |
DeepLabCutを使って、速度や移動距離を求める:D |
https://qiita.com/mantohihihihi/items/0ed955a0e9477d794b07
|
ddeeplabcut |
2023-03-26 15:36:15 |
python |
Pythonタグが付けられた新着投稿 - Qiita |
Pythonバックエンドでmatplotlibで描画された画像をクライアントサイド(React)に表示する方法 |
https://qiita.com/windfall/items/7609856ac7c6f378f435
|
bytesio |
2023-03-26 15:02:46 |
js |
JavaScriptタグが付けられた新着投稿 - Qiita |
Javascriptについて |
https://qiita.com/koooen/items/1fc2de7e2e6ea051de2b
|
const |
2023-03-26 15:40:07 |
js |
JavaScriptタグが付けられた新着投稿 - Qiita |
【G's EXPANSION】React実践プログラムを受講してみた |
https://qiita.com/stkntr/items/3eedd8d00513af224789
|
gsexpansion |
2023-03-26 15:12:10 |
AWS |
AWSタグが付けられた新着投稿 - Qiita |
知識いろいろ箱 |
https://qiita.com/CloudMonkey/items/def5de271da95f2ca66c
|
負荷 |
2023-03-26 15:44:36 |
AWS |
AWSタグが付けられた新着投稿 - Qiita |
知識データベース】S3 |
https://qiita.com/CloudMonkey/items/7d3e54d6065dfe6ea127
|
一定期間 |
2023-03-26 15:34:20 |
Azure |
Azureタグが付けられた新着投稿 - Qiita |
Azure Databricks でのクラスター起動が Instances Unreachable エラーで失敗する際のトラブルシューティング |
https://qiita.com/samskeyti/items/b40e5d3e91bed4977ab1
|
azuredatabricks |
2023-03-26 15:53:47 |
海外TECH |
DEV Community |
TypeScript CRUD Rest API, using: Nest.js, TypeORM, Postgres, Docker and Docker Compose |
https://dev.to/francescoxx/typescript-crud-rest-api-using-nestjs-typeorm-postgres-docker-and-docker-compose-33al
|
TypeScript CRUD Rest API using Nest js TypeORM Postgres Docker and Docker ComposeLet s create a CRUD Rest API in Typescript using NestJS NodeJS framework TypeORM ORM Object Relational Mapper Postgres relational database Docker for containerization Docker Compose If you prefer a video version All the code is available in the GitHub repository link in the video description IntroHere is a schema of the architecture of the application we are going to create We will create endpoints for basic CRUD operations CreateRead allRead oneUpdateDeleteHere are the steps we are going through Create a new NestJS applicationCreate a new module for the users with a controller a service and an entityDockerize the applicationCreate docker compose yml to run the application and the databaseTest the application with Postman and TableplusWe will go with a step by step guide so you can follow along Requirements Node installed I m using v Docker installed and running Optional Postman and Tableplus to follow along but any testing tool will workNestJS CLI command below Create a new NestJS applicationWe will create our project using the NestJS CLIif you don t have the NestJS CLI installed you can install it with npm install g nestjs cliThis will install the NestJS CLI globally so you can use it from anywhere Then you can create move to your workspace folder and create a new NestJS application with you can replace nest crud app with what you want nest new nest crud appJust hit enter to go with the default options This will create a new project for you it will take a while Step into the directory cd nest crud appNow install the dependencies we need npm i pg typeorm nestjs typeorm nestjs configpg Postgres driver for NodeJStypeorm ORM for NodeJS nestjs typeorm NestJS module for TypeORM nestjs config NestJS module for configurationOnce it s done open the project in your favorite editor I m using VSCode code Before we start coding let s test if everything is working npm startAnd we should see something like that Now you can stop the server with Ctrl C Create the NestJS applicationNow we are going to work on the NestJS application Let s create a new module a controller a service and an entity nest g module usersnest g controller usersnest g service userstouch src users user entity tsThis will create the following files and more test files we will not use src users users module tssrc users users controller tssrc users users service tssrc users user entity tsYour folder structure should look like that Now let s work on these files User EntityOpen the file src users user entity ts and populate it like that import Entity PrimaryGeneratedColumn Column from typeorm Entity export class User PrimaryGeneratedColumn id number Column name string Column email string Explanation We are using the decorator Entity to tell TypeORM that this is an entityWe are using the decorator PrimaryGeneratedColumn to tell TypeORM that this is the primary key of the tableWe are using the decorator Column to tell TypeORM that this is a column of the tableWe are creating a User entity with columns id name and email User ServiceOpen the file src users users service ts and populate it like that import Injectable from nestjs common import InjectRepository from nestjs typeorm import Repository from typeorm import User from user entity Injectable export class UserService constructor InjectRepository User private userRepository Repository lt User gt async findAll Promise lt User gt return this userRepository find async findOne id number Promise lt User gt return this userRepository findOne where id async create user Partial lt User gt Promise lt User gt const newuser this userRepository create user return this userRepository save newuser async update id number user Partial lt User gt Promise lt User gt await this userRepository update id user return this userRepository findOne where id async delete id number Promise lt void gt await this userRepository delete id Explanation We are using the decorator Injectable to tell NestJS that this is a serviceWe are using the decorator InjectRepository User to tell NestJS that we want to inject the repository of the User entityWe are using the decorator Repository User to tell NestJS that we want to inject the repository of the User entityWe are creating a UserService with methods findAll findOne create update and delete User ControllerOpen the file src users users controller ts and populate it like that import Controller Get Post Body Put Param Delete NotFoundException from nestjs common import UsersService from users service import User from user entity Controller users export class UsersController constructor private readonly usersService UsersService get all users Get async findAll Promise lt User gt return this usersService findAll get user by id Get id async findOne Param id id number Promise lt User gt const user await this usersService findOne id if user throw new NotFoundException User does not exist else return user create user Post async create Body user User Promise lt User gt return this usersService create user update user Put id async update Param id id number Body user User Promise lt any gt return this usersService update id user delete user Delete id async delete Param id id number Promise lt any gt handle error if user does not exist const user await this usersService findOne id if user throw new NotFoundException User does not exist return this usersService delete id Explanation We are using the decorator Controller users to tell NestJS that this is a controller and that the route is users We are defining the constructor of the class and injecting the UserServiceWe are defining methods findAll findOne create update and delete decorated with the HTTP method we want to use and we are using the UserService to call the corresponding method User ModuleOpen the file src users users module ts and populate it like that import Module from nestjs common import UserController from users controller import UserService from users service import TypeOrmModule from nestjs typeorm import User from user entity Module imports TypeOrmModule forFeature User controllers UserController providers UserService export class UsersModule Explanation We are importing the TypeOrmModule and the User entity UserController and UserService are already imported We are using the decorator Module to tell NestJS that this is a moduleWe add the TypeOrmModule forFeature User to the imports array to tell NestJS that we want to use the User entity Update the Main ModuleOpen the file src app module ts and populate it like that import Module from nestjs common import AppController from app controller import AppService from app service import UsersModule from users users module import TypeOrmModule from nestjs typeorm import ConfigModule from nestjs config Module imports ConfigModule forRoot UsersModule TypeOrmModule forRoot type process env DB TYPE as any host process env PG HOST port parseInt process env PG PORT username process env PG USER password process env PG PASSWORD database process env PG DB entities dirname entity ts js synchronize true controllers AppController providers AppService export class AppModule Explanation We are importing the ConfigModule the UsersModule and the TypeOrmModuleWe are importing the ConfigModule UsersModule and TypeOrmModule in the imports arrayFor TypeOrmModule we are using the method forRoot to tell NestJS that we want to use the default connection and we define some environment variables to connect to the database We will set the in the docker compose yml file soon the synchronize option is set to true so that the database schema is automatically updated when the application is started Dockerize the applicationLet s create files to dockerize the application a Dockerfile and a dockerignore file touch Dockerfile dockerignore docker compose yml dockerignoreA dockerignore file is used to tell Docker which files and directories to ignore when building the image If you are familiar with the gitignore file it works the same way Open the file dockerignore and populate it like that node modulesdist gitThis will tell Docker to ignore the node modules dist and git directories when building the image DockerfileA Dockerfile is a text document that contains all the commands a user could call on the command line to assemble an image Open the file Dockerfile and populate it like that FROM node WORKDIR appCOPY package json RUN npm installCOPY RUN npm run buildEXPOSE CMD npm run start prod Explanation FROM node is used to tell Docker which image to use as a base image WORKDIR is the directory where the commands will be executed In our case it s the app directory COPY package json is used to copy the package json and package lock json files to the app directory RUN npm install is used to install the dependencies COPY is used to copy all the files from the current directory to the app directory RUN npm run build is used to build the application EXPOSE is used to expose the port to the host CMD is used to execute a command when the container is started in our case it s npm run start prod docker compose yml fileWe will use docker compose to run the application and the database Populate the file docker compose yml like that version services nestapp container name nestapp image francescoxx nestapp build ports environment DB TYPE postgres PG USER postgres PG PASSWORD postgres PG DB postgres PG PORT PG HOST db depends on db db container name db image postgres environment POSTGRES USER postgres POSTGRES PASSWORD postgres POSTGRES DB postgres ports volumes pgdata var lib postgresql datavolumes pgdata Explanation We are using the version of the docker compose yml file formatWe are defining services nestapp and dbThe nestapp service is used to run the NestJS applicationThe db service is used to run the Postgres databaseThe nestapp service depends on the db service so that the db service is started before the nestapp serviceFor the nestapp service container name is used to set the name of the containerimage is used to set the image to use in our case it s francescoxx nestapp change francescoxxx with your docker hub usernamebuild is used to build the image from the Dockerfile we are using the current directory as the build context ports is used to expose the port to the hostenvironment is used to set the environment variables DB TYPE PG USER PG PASSWORD PG DB PG PORT PG HOST these variables will be used by the application to connect to the databasedepends on is used to tell docker compose that the db service must be started before the nestapp service For the db service container name is used to set the name of the containerimage is used to set the image to use in our case it s postgres environment is used to set the environment variables POSTGRES USER POSTGRES PASSWORD POSTGRES DBports is used to expose the port to the hostvolumes is used to mount a volume to the container In our case we are mounting the pgdata volume to the var lib postgresql data directory We also define the pgdata volume at the end of the file Run the Postgres serviceTo run the Postgres service we will use the docker compose command docker compose up d dbThis will run the db service in detached mode To check if the service is running we can use the docker ps command docker ps aWe should see something like that img alt docker ps a lt br gt CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES lt br gt efaca postgres quot docker entrypoint s… quot seconds ago Up seconds gt tcp db height src dev to uploads s amazonaws com uploads articles gobjlhimofwjobk png width But let s check it with TablePlus Open the TablePlus application and connect to the database by creating a new Postgres connection You can use the UI and set Host localhostPort Username postgresPassword postgresDatabase postgresThen hit the Connect button at the bottom right Now we are ready to build the Nest app image and run the application Build the Nest app imageTo build the Nest app image we will use the docker compose command docker compose buildThis will build the image from the Dockerfile To check if the image is built we can use the docker images command img alt docker images lt br gt REPOSITORY TAG IMAGE ID CREATED SIZE lt br gt francescoxx nestapp c About an hour ago GB lt br gt postgres dbfa hours ago MB height src dev to uploads s amazonaws com uploads articles ulccmqlyhuezxasggj png width Run the Nest app serviceTo run the Nest app service we will use the docker compose command docker compose up Test the applicationTo Test the application we can use the Postman or any other API client First of all let s test if the app is running Open Postman and create a new GET request Get all usersTo get all users we can make a GET request to localhost users If we see an empty array it means that its working Create a userTo create a user we can make a POST request to localhost users In the body we can use the raw JSON format and set the following data name aaa email aaa mail You can create more users with the following data name bbb email bbb mail name ccc email ccc mail Get all the three usersTo get all the three users we can make a GET request to localhost users Get a user by idTo get a single user we can make a GET request to localhost users Update a userTo update a user we can make a PUT request to localhost users Let s change the name from bbb to Francesco and the email from bbb mail to francesco mail name Francesco email francesco mail Delete a userFinally to delete a user we can make a DELETE request to localhost users The answer comes directly from the database Final test with TablePlusLet s check if the data is correctly stored in the database As a final test let s go back to TablePlus and check if the data has been updated ConclusionWe made it We have built a CRUD rest API in TypeScript using NestJS NodeJS framework TypeORM ORM Object Relational Mapper Postgres relational database Docker for containerization Docker Compose If you prefer a video version All the code is available in the GitHub repository link in the video description That s all If you have any question drop a comment below Francesco |
2023-03-26 06:16:52 |
海外ニュース |
Japan Times latest articles |
With U.S. trip, Taiwan leader may be aiming to temper China’s ire, ex-diplomat says |
https://www.japantimes.co.jp/news/2023/03/26/asia-pacific/politics-diplomacy-asia-pacific/taiwan-ait-william-stanton-interview/
|
With U S trip Taiwan leader may be aiming to temper China s ire ex diplomat saysWilliam Stanton former head of the American Institute of Taiwan says President Tsai Ing wen may see visit as way of avoiding increased tensions with Beijing |
2023-03-26 15:44:17 |
海外ニュース |
Japan Times latest articles |
Conservatives in LDP take issue with gender identity clause in LGBT bill |
https://www.japantimes.co.jp/news/2023/03/26/national/politics-diplomacy/ldp-lgbt-bill/
|
hurdle |
2023-03-26 15:12:44 |
ニュース |
BBC News - Home |
Putin: Russia to station nuclear weapons in Belarus |
https://www.bbc.co.uk/news/world-europe-65077687?at_medium=RSS&at_campaign=KARANGA
|
nuclear |
2023-03-26 06:51:59 |
ニュース |
BBC News - Home |
The Papers: PM's crime 'blitz' and children 'strip-searched' |
https://www.bbc.co.uk/news/blogs-the-papers-65078444?at_medium=RSS&at_campaign=KARANGA
|
curtail |
2023-03-26 06:28:38 |
IT |
週刊アスキー |
不二家の「カントリーマアムチョコまみれ」に抹茶味が登場! パッケージやたくさんの仕掛けにも注目 |
https://weekly.ascii.jp/elem/000/004/129/4129482/
|
新フレーバー |
2023-03-26 15:45:00 |
コメント
コメントを投稿