sequelize.js_下一个带有sequelize Web应用程序的js全栈Web开发

sequelize.js

The help and supports from Next.js community has made a tremendous impact on how it grows to become one of the most popular React Framework right now. There are many good examples from Next.js and the community that are worth to see in this link.

Next.js社区的帮助和支持对它如何发展成为当前最受欢迎的React Framework之一产生了巨大影响。 Next.js和社区中有很多很好的例子,值得在此链接中看到。

There are several of ORM engines in Node.js ecosystem such as Sequelize, TypeORM and Objection. I had working with Sequelize before and I want to share to you about how I have managed to combine it with Next.js.

Node.js生态系统中有几种ORM引擎,例如SequelizeTypeORMObjection 。 之前我曾与Sequelize合作,我想与大家分享我如何设法将其与Next.js结合在一起。

Request and Response can be used in the API pages in your project without any addition of custom server like Express.js. This is the explanation from Next.js API route support.

可以在项目的API页面中使用“ 请求响应” ,而无需添加任何自定义服务器(如Express.js)。 这是Next.js API路由支持的说明

/** ./pages/api/hello.js **/
export default (req, res) => {
res.statusCode = 200;
res.json({ name: "John Doe" });
};

So far this is one of my favourite features from the latest Next.js version. This feature can be use as a Full-Stack Development, and could be an effective replacement to custom servers in Next.js app such as express. It can be use to connect into external API or backend system to access databases like MongoDB / NoSQL or MySQL / SQL.

到目前为止,这是最新的Next.js版本中我最喜欢的功能之一。 此功能可以用作全栈开发,并且可以有效替代Next.js应用程序中的自定义服务器,例如express。 它可以用来连接外部API或后端系统,以访问MongoDB / NoSQL或MySQL / SQL等数据库。

具有Sequelize Web应用程序的Next.js (Next.js with Sequelize web application)

Requirements are Sequelize-cli, Database drivers, JWT (jsonwebtoken) and of course Next.js with the React library. For this project purpose this is the complete package.json setup :

要求是Sequelize-cli数据库驱动程序JWT( jsonwebtoken ) ,当然还有带有React库的Next.js。 对于此项目,这是完整的package.json设置:

package.json for Next.js and Sequelize
用于Next.js和Sequelize的package.json

Setup Note: This application uses SQLite in local development and PostGres in production for the RDBMS. It is up to you if you want to use MySQL both in local and production. You can skip to install SQLite parts and take a look at the table schema files for the database structure.

设置说明: 此应用程序 本地 开发中 使用 SQLite 生产中 为RDBMS 使用 PostGres 如果要在本地和生产环境中使用MySQL,则取决于您。 您可以跳过安装SQLite部件的过程,并查看数据库结构的表模式文件。

Next.js设定 (Next.js Setup)

npx create-next-app or just create-next-app and type your project name nextjs-sequelize or any name. Install npm i create-next-app if you haven’t.

npx create-next-app或仅create-next-app并键入您的项目名称nextjs-sequelize或任何名称。 如果尚未安装,请安装npm i create-next-app

Create Next.js in the teminal create-next-app nextjs-sequelize
create-next-app nextjs-sequelize
创建下一个应用程序nextjs-sequelize

Add other libraries for the project : bcryptjs, js-cookie, jsonwebtoken, sqlite3, mysql2, next-connect, nprogress, pg, pg-hstore, postcss-preset-env, sequelize.

为项目添加其他库: bcryptjsjs-cookiejsonwebtokensqlite3, mysql2next-connectnprogresspgpg-hstorepostcss-preset-envsequelize

yarn add bcryptjs js-cookie jsonwebtoken sqlite3 mysql2 next-connect nprogress pg pg-hstore postcss-preset-env sequelize

or

要么

npm i bcryptjs js-cookie jsonwebtoken sqlite3 mysql2 next-connect nprogress pg pg-hstore postcss-preset-env sequelize
add libraries to the project
add libraries to the project
将库添加到项目

创建.env文件变量 (Create .env file variables)

.env.local file for local development
.env.local文件用于本地开发

顺序设置 (Sequelize Setup)

Setup Note: This application uses sequelize@^5.21.11 which is very different prior to ^6.2.* version of sequelize and sequelize-cli.

设置说明: 此应用程序使用 sequelize@^5.21.11 ,这 与sequ​​elize和sequelize-cli的 ^6.2.* 版本 之前非常不同

使用Sequelize-cli命令 (Using Sequelize-cli command)

Install CLI withnpm i -g sequelize-cli or yarn global add sequelize-cli

使用npm i -g sequelize-cli或CLI yarn global add sequelize-cli安装npm i -g sequelize-cli安装CLI

If we use sequelize-cli commands, at first we will be ask for executing sequelize init that will generate some files in our root directory. Generated files will be used to make Sequelize modules run with the project.

如果我们使用sequelize-cli命令,首先会要求我们执行sequelize init ,它将在根目录中生成一些文件。 生成的文件将用于使Sequelize模块与项目一起运行。

Image for post
Sequelize init generated files
排序初始化生成的文件

These files and directories generated via Sequelize-cli command. If you want to move and organise into a different directory, use .sequelizerc like the one I used in this project.

这些文件和目录是通过Sequelize-cli命令生成的。 如果要移动并组织到另一个目录中,请使用.sequelizerc就像我在本项目中使用的那样。

使用.sequelizerc文件 (Using .sequelizerc file)

Sequelize have a project setup file that you can you use to organised your project directory. Meaning that you can put and setup your Sequelize files in a specific directory like the way you want it to be in a file called .sequelizerc. Below is the sample that Sequelize files and directory will be generated in a directory named /db in your project root. Just type sequelize init to generate Sequelize project from a .sequelizerc file.

Sequelize有一个项目设置文件,可用于组织项目目录。 这意味着您可以将Sequelize文件放置并设置在特定目录中,就像您希望将其保存在名为.sequelizerc的文件中一样 。 下面是在项目根目录中名为/db的目录中生成Sequelize文件和目录的示例。 只需键入sequelize init即可从.sequelizerc文件生成Sequelize项目。

const path = require('path');
module.exports = {
'config': path.resolve('db/config', 'config.js'),
'models-path': path.resolve('db', 'models'),
'seeders-path': path.resolve('db', 'seeders'),
'migrations-path': path.resolve('db', 'migrations')
};
Initialing Sequelize in our Next.js project
Initialing Sequelize in our Next.js project root
在我们的Next.js项目根目录中初始化Sequelize
Image for post
Generated Sequelize files and directory in /db/ directory inside Next.js project root
Next.js项目根目录下/ db /目录中生成的Sequelize文件和目录

Open up config.js in editor and add an export default to the files like these one and replace the config and put your env variables from .env.local :

在编辑器中打开config.js并将导出默认值添加到这些文件中,然后替换配置并从.env.local放入您的env变量:

Sequelize config.js
序列化config.js
Sequelize config.js with Node .env variables
使用Node .env变量对config.js进行排序

Sequelize, Sqlite3和Mysql2模块的 安装程序安装 (Setup install for Sequelize, Sqlite3 and Mysql2 modules)

Sequelize-cli will be use for generating migrations and models setup. More information about the features in this link.

Sequelize-cli将用于生成迁移和模型设置。 有关此链接中功能的更多信息。

Install sequelize-cli

安装sequelize-cli

npm i -g sequelize-cli or yarn global add sequelize-cli

npm i -g sequelize-cliyarn global add sequelize-cli

Install sequelize and type sequelize init

安装sequelize并键入sequelize init

npm i sequelize or yarn add sequelize and sequelize init

npm i sequelizeyarn add sequelizesequelize init

Install sqlite3 driver

安装sqlite3驱动程序

npm i sqlite3 or yarn add sqlite3

npm i sqlite3yarn add sqlite3

Install mysql2 driver

安装mysql2驱动

npm i mysql2 or yarn add mysql2

npm i mysql2yarn add mysql2

Create a SQLite3 database in /db/nextjs-sequelize.db and continue for migration setup.

在/db/nextjs-sequelize.db中创建一个SQLite3数据库,然后继续进行迁移设置。

- Users model

-用户模型

sequelize model:create --name users --attributes firstName:string,lastName:string,username:string,password:string,email:string,phoneNumber:string,gender:string,status:boolean

- Users model seed

-用户建模种子

sequelize seed:generate --name users

- Posts model

-帖子模型

sequelize model:create --name posts --attributes userId:integer,title:string,slug:string,content:text,status:boolean

- Posts model seed

-发布模型种子

sequelize seed:generate --name posts

- Jobs model

-工作模式

sequelize model:create --name jobs --attributes userId:integer,title:string,slug:string,content:text,emailTo:string,reportManager:string,dateLimit:date,status:boolean

- Jobs model seed

-乔布斯模型种子

sequelize seed:generate --name jobs
Sequelize creating Users, Posts and Jobs Models
Sequelize creating Users, Posts and Jobs Models
顺序创建用户,职位和工作模型
Sequelize creating Users, Posts and Jobs Seeds
Sequelize creating Users, Posts and Jobs Seeds
顺序创建用户,职位和工作种子
Sequelize migrations, seeds files and directories
Sequelize migrations, seeds files and directories in Next.js root project
在Next.js根项目中安排迁移,种子文件和目录的顺序

Open seeders files and modify to add arrays of data items.

打开种子服务器文件,然后进行修改以添加数据项数组。

- ./seeders/xxxxxxxxxxx-users.js

-./seeders/xxxxxxxxxxx-users.js

./seeders/xxxxxxxxxxx-users.js
./seeders/xxxxxxxxxxx-users.js

./seeders/xxxxxxxxxxx-posts.js

./seeders/xxxxxxxxxxx-posts.js

./seeders/xxxxxxxxxxx-posts.js
./seeders/xxxxxxxxxxx-posts.js

./seeders/xxxxxxxxxxx-jobs.js

./seeders/xxxxxxxxxxx-jobs.js

./seeders/xxxxxxxxxxx-jobs.js
./seeders/xxxxxxxxxxx-jobs.js

Sequelize database migration and seed command

序列化数据库迁移和种子命令

sequelize db:migrate to execute database migrations.

sequelize db:migrate以执行数据库迁移。

sequelize db:seed:all to execute all table seeders.

sequelize db:seed:all以执行所有表种子。

Sequelize undo database migration and seed command

序列化撤消数据库迁移和种子命令

sequelize db:migrate:undo:all to undo database migrations.

sequelize db:migrate:undo:all以撤消数据库迁移。

sequelize db:seed:undo:all to undo seeders.

sequelize db:seed:undo:all以撤消种子。

Sequelize Seeders
Sequelize Seeders
播种者的后代

- Add Associations * (execute after you edited the association migration files)

-添加关联 *(在编辑关联迁移文件后执行)

sequelize migration:generate --name add-post-associate
./migrations/xxxxxxxxxxx-add-posts-associate.js
./migrations/xxxxxxxxxxx-add-posts-associate.js
sequelize migration:generate --name add-jobs-associate
./migrations/xxxxxxxxxxx-add-jobs-associate.js
./migrations/xxxxxxxxxxx-add-jobs-associate.js

sequelize db:migrate to execute database associate migrations.

sequelize db:migrate以执行数据库关联迁移。

Open up ./models/index.js that previously generated from sequelize init and modified the codes.

打开先前从sequelize init生成的./models/index.js并修改代码。

./models/index.js
./models/index.js

Create .env.development.local and put your DB credentials see .env.local.example

创建.env.development.local并将您的数据库凭据放入.env.local.example

DB_HOST=myhost_local
DB_USER=myuser_local
DB_PASS=mypassword_local
DB_NAME=mydatabase_localJWT_KEY="secretOrKeyJWTRandom"

Start the Next.js dev server and open up http://localhost:3000/

启动Next.js开发服务器并打开 http:// localhost:3000 /

yarn dev to start Next.js the dev server and notice the .env.development.local loaded on the application start up.

yarn dev启动Next.js开发服务器,并注意到在应用程序启动时加载的.env.development.local。

yarn dev load .env.development.local
yarn dev
纱线开发

Deployment on Vercel

在Vercel上部署

Install Vercel Cli npm i -g vercel or yarn add global vercel and see this link for available commands. This will enables you to instant cloud deployment and local development. Follow the instruction and press enter for your setup choice. Just type vercel --prod to deploy or update the changes in your root terminal.

安装Vercel Cli npm i -g vercelyarn add global vercel ,请参阅此链接以获取可用命令。 这将使您能够即时进行云部署本地开发 。 按照说明进行操作,然后按Enter键选择设置。 只需输入vercel --prod即可部署或更新根终端中的更改。

Vercel Cli for deploy project to Vercel Hosting
Deploy project to Vercel
将项目部署到Vercel

Production environment setup

生产环境设置

Check your default .env.local.example in your root directory and match the variables into vercel project settings. Below is the example of the .env.

在根目录中检查默认的.env.local.example并将变量匹配到vercel项目设置中。 以下是.env的示例。

DB_HOST="db/nextjs-sequelize.db"
DB_USER=null
DB_PASS=null
DB_NAME="nextjs-sequelize"
JWT_KEY="secretOrKeyJWTRandom"

Add your database credentials in .env to pointing to the database in your production server. If you using Vercel hosting, add your env variables in the production tabs of project settings page. These will be auto encrypted and available for used in the production .env of our app. Below is the setup .env production for our remote database credential on Vercel :

.env中添加数据库凭据,以指向生产服务器中的数据库。 如果您使用Vercel托管,请在项目设置页面的生产选项卡中添加环境变量。 这些将自动加密,并可以在我们的应用程序的生产.env中使用。 以下是我们在Vercel上的远程数据库凭证的设置.env生产:

Image for post
.env production in vercel hosting
.env在Vercel托管中的生产

Demos :

演示:

Source Code :

源代码 :

Note : The source code on GitHub is a full version with users, posts and jobs models and use SQLite database on the development / local server. Login with any email accounts in the demos using passkey “password”. The one on the demo is a cut version due to limit of serverless functions on Vercel and uses Postgres database on elephantsql.com. Use the branch origin/serverless if you want to use it and deploy on Vercel hosting.

注意: GitHub上 的源代码 是完整版本,包含用户,职位和职位模型,并在开发/本地服务器上使用SQLite数据库。 使用密码“ password”登录演示中的任何电子邮件帐户。 由于Vercel上无服务器功能的限制, 演示 版中 的一个 是简化版,并使用 Elephantsql.com 上的Postgres数据库 如果要 使用分支 起源/无服务器 ,并在Vercel托管上进行部署,请使用它。

有待改进的地方: (Things to improve :)

  • Make field aliases in Sequelize to obfuscate and not to expose the real name of your database field names.

    在Sequelize中将字段别名设置为混淆,而不是公开数据库字段名称的真实名称。

  • Consider using UUID for the primary key that can be handled by Sequelize.

    考虑将UUID用作Sequelize可以处理的主键。

  • Consider to make separate presentational container to handle all the Next.js page logics involved in the views components.

    考虑制作单独的演示容器来处理视图组件中涉及的所有Next.js页面逻辑。

  • Setup a React State Management like Redux and combined it with Redux-Saga so you can have that fancy loader to the application.

    设置一个像Redux这样的React State Management,并将其与Redux-Saga结合使用,这样您就可以将花哨的加载程序添加到应用程序中。

  • Use Next.js Absolute Imports and Aliases for importing components.

    使用Next.js 绝对导入和别名 用于导入组件。

  • Make versioning to the API pages such as /pages/api/v1/**/**.js to track changes and features.

    对API页面(例如/pages/api/v1/**/**.js进行版本控制,以跟踪更改和功能。

  • Make use of next-seo to improve your SEO pages in the SERP.

    利用next-seo改善SERP中的SEO页面。

  • Setup a Reverse Proxy Server such as Nginx or Apache for your Web Application in production.

    在生产中为您的Web应用程序设置一个反向代理服务器,例如Nginx或Apache。

  • Use PM2 / Production Manager for production and clustering system.

    PM2 / Production Manager用于生产和集群系统。

References:1. Sequelize : https://sequelize.org/2. Next.js : https://nextjs.org/docs/3. Jwt : https://jwt.io/

参考文献:1。 Sequelize: https : //sequelize.org/ 2. Next.js: https : //nextjs.org/docs/ 3. Jwt: https : //jwt.io/

TL; DR (TL;DR)

Next.js : Since it’s inception, Next.js features comes with an API pages that can be used as a local API to access your data beside all the new and rich features. Server Side Rendering is one of the best feature on Next.js

Next.js 从诞生之日起,Next.js功能就附带了API页面,除了所有新的丰富功能之外,这些页面还可以用作本地API来访问数据。 服务器端渲染是Next.js的最佳功能之一

Sequelize : A multi SQL dialect ORM (Object Relation Mapping) for Node.js ecosystem or in Express.js framework application. It can be use to connect to your RDBMS databases. Common queries methods in ORM are : hasMany , belongsTo , hasOne , and belongsToMany.

Sequelize 针对Node.js生态系统或Express.js框架应用程序的多SQL方言ORM(对象关系映射)。 它可以用于连接到RDBMS数据库。 ORM中常见的查询方法是: hasManybelongsTohasOnebelongsToMany

翻译自: https://medium.com/@defrian.yarfi/next-js-with-sequelize-web-application-a-full-stack-web-development-a0051074e998

sequelize.js

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值