完全なスタックのSAPPER&SQLiteのシーケンシャルPT.1


ようこそMongoDB/mongooseとのインターネット上での表現のためのデータベースとしてたくさんのチュートリアルです.リレーショナルデータベースを探索することにしました.私の心に入った最初のことはSQLiteでした.そして驚いたことに、私はサパーで動作する何かを見つけることができませんでした.
このチュートリアルでは、2つの部分で構成され、最初の1つは、明示的なバックエンド、SQLiteのDB、コントローラ、すべてのジャズについて懸念している第2の部分は、SapperでSvelteフロントエンドの統合をガイドします.
これらの2つの最小限であるが、強力なテクノロジーの私の統合の最終的な結果は、ここにありますhttps://github.com/gevera/sapper_sqlite_crud あなたはスピンとそれを取ることができます
npx degit gevera/sapper_sqlite_crud
npm i
npm run dev

ゼロから作る
デフォルトのSAPPERプロジェクトを作成し、それをtypescriptに変換し、必要な依存関係をインストールする
npx degit "sveltejs/sapper-template#rollup" sapper_sqlite
cd sapper_sqlite
node scripts/setupTypeScript.js
npm i
まず第一に、我々の依存関係に加えて、デフォルトのポルカの代わりに表現し、SQLiteデータベースとシーケンシャルORMを追加しましょう.
npm i express sqlite3 sequelize
npm remove polka @types/polka
彼らのためにタイプを加えましょう
npm i -D @types/express @types/node @types/sqlite3 @types/sequelize
フォルダを作成するsrc フォルダdb . を作成し、sqliteDb.ts ファイルを入力します.ここでは、シーケンス化とエクスポートのインポート自体と非同期db でデータベースを初期化する関数./src/db 名前の下のフォルダdatabase.sqlite 私たちはサーバーファイルを変更するときに少しこの関数を使用します.
import { Sequelize } from 'sequelize';

export const sequelize = new Sequelize({
    dialect: 'sqlite',
    storage: './src/db/database.sqlite',
});

export const db = async () => {
    try {
        await sequelize.authenticate();
        console.log('Connection to sqliteDB has been established successfully.');
    } catch (error) {
        console.error('Unable to connect to the database:', error);
    }
};
次に、ユーザモデルを作成する必要がありますUser.ts インModels フォルダ
import { UUIDV4, DataTypes } from "sequelize";
import { sequelize } from "../sqliteDb";

export const UserModel = sequelize.define("User", {
  id: {
    type: DataTypes.UUID,
    defaultValue: UUIDV4,
    primaryKey: true,
  },
  name: {
    type: DataTypes.STRING,
    allowNull: false,
    unique: true,
  },
  profession: {
    type: DataTypes.STRING,
    defaultValue: "programmer",
  },
});
注:インポートUUIDV4 各ユーザーの一意のプライマリIDを作成するには.これは非常にマングーススキーマに似ています.
我々の要求を処理するためにコントローラが必要ですcontrollers ディレクトリsrc を追加し、userControllers.ts ファイル.ここではすべての魔法のサーバーとデータベースの間に発生します.私はいくつかの理由でより多くのその後、mongoose構文をシーケンス化したいです.それは簡単できれいだと思います.
import { UserModel } from '../db/Models/User';
import { sequelize } from '../db/sqliteDb';

export const getAllUsers = async (req, res, next) => {
    try {
        await sequelize.sync();
        const users = await UserModel.findAll();
        res.json({ success: true, data: users }).status(200);

    } catch (e) {
        console.log(e);
        res.json({ success: false, message: 'Failed to find users' }).status(500);
    }
}

export const createAUser = async (req, res, next) => {

    try {
        await sequelize.sync();
        const { name, profession } = req.body;
        const newUser = await UserModel.create({ name, profession });
        res.json({ success: true, data: newUser }).status(200);
    } catch (e) {
        console.log(e);
        res.json({ success: false, message: 'Failed to create a new user' }).status(500);
    }
}

export const getAUser = async (req, res, next) => {
    try {
        await sequelize.sync();
        const user = await UserModel.findAll({
            where: {
                id: req.params.id
            }
        });
        if (user.length) {
            res.json({ success: true, data: user }).status(200);
        } else {
            res.json({ success: false, message: 'Failed to find user' }).status(404);
        }

    } catch (e) {
        console.log(e);
        res.json({ success: false, message: 'Failed to find user' }).status(500);
    }
}

export const deleteAUser = async (req, res, next) => {
    try {
        await sequelize.sync();
        const user = await UserModel.destroy({
            where: {
                id: req.params.id
            }
        });
        if (user) {
            res.json({ success: true, message: 'User deleted!' }).status(204);
        } else {
            res.json({ success: false, message: 'Failed to find user' }).status(404);
        }

    } catch (e) {
        console.log(e);
        res.json({ success: false, message: 'Failed to delete user' }).status(500);
    }
}

export const updateAUser  = async (req, res, next) => {
    try {
        await sequelize.sync();
        const user = await UserModel.update({ ...req.body }, {
            where: {
                id: req.params.id
            }
        });
        if (user.length) {
            res.json({ success: true, message: 'User updated!', data: user }).status(204);
        } else {
            res.json({ success: false, message: 'Failed to find user' }).status(404);
        }
    } catch (e) {
        console.log(e);
        res.json({ success: false, message: 'Failed to update user' }).status(500);
    }
}
最後にserver.ts ファイルをsrc ディレクトリ.
スイッチポルカを表現する.インポートdb 関数を実行して実行します.また、JSONとUrlencodedを有効にする必要がありますので、POST/PUTリクエストの本体を解析できます.
以前に作成したコントローラを取得し、対応するルートに適用します.
import sirv from "sirv";
import express from "express";
import compression from "compression";
import * as sapper from "@sapper/server";
import { db } from "./db/sqliteDb";
import {
    getAllUsers,
    createAUser,
    getAUser,
    updateAUser,
    deleteAUser
} from './controllers/userControllers';

const { PORT, NODE_ENV } = process.env;
const dev = NODE_ENV === "development";

db();

const app = express();

app.use(express.urlencoded({ extended: true }));
app.use(express.json());

app.get('/api', getAllUsers);
app.post('/api', createAUser);
app.get('/api/:id', getAUser);
app.put('/api/:id', updateAUser);
app.delete('/api/:id', deleteAUser);

app
  .use(
    compression({ threshold: 0 }),
    sirv("static", { dev }),
    sapper.middleware()
  )
  .listen(PORT, () => {
    console.log("Express is up and running!");
  });
最初のランでdatabase.sqlite ファイルはdb フォルダ.あなたが打つならばhttp://localhost:3000/api 我々は得る
{
  "success": true,
  "data": []
}
大成功!私たちのサパーアプリは永続的なデータベースと完全に作業休息APIを丸有している.