Express를 사용하여 Fauna 및 Node.js 시작하기

동물 군은 무엇입니까?



FaunaDB is a global cloud database created to integrate with the JAMStack and modern serverless architecture. FaunaDb is not just a flexible and transactional database; it is a developer-friendly database that exposes you to building a fast, secured, and scalable cloud API with native GraphQL.



FaunaDB의 장점 중 일부는 데이터베이스 인프라의 핵심에서 처리되기 때문에 데이터베이스 프로비저닝, 확장, 샤딩, 복제 또는 정확성에 대해 다시 걱정할 필요조차 없다는 것입니다.

이 기사에서는 완벽하게 작동하는 API를 구축하고 Node.js 및 FaunaDB를 사용하여 널리 사용되는 CRUD 애플리케이션을 시연하여 FaunaDB를 실질적으로 탐색합니다.

바로 구축에 들어가 봅시다!

1단계: 동물군 데이터베이스 설정



CRUD 앱을 시작하려면 Fauna 대시보드에서 CRUD 앱용 데이터베이스를 생성해야 합니다.

계정을 만들려면 공식 웹 사이트로 이동하여 등록하십시오https://dashboard.fauna.com/accounts/register.

대시보드에서 "NEW DATABASE" 버튼을 클릭하고 데이터베이스 이름을 입력한 다음 SAVE 버튼을 누릅니다.



데이터베이스를 미리 채울지 여부와 다른 데이터베이스에서 Fauna로 마이그레이션하는 경우 팁이 있습니다.

지금은 데이터베이스 이름을 입력하고 "SAVE" 버튼을 누릅니다. 그러면 아래와 같은 화면이 나타납니다.



2단계: Fauna API 키 생성



데이터베이스를 CRUD 앱에 연결하려면 Fauna API 키를 생성해야 합니다. 이렇게 하려면 Fauna 사이드바(화면 왼쪽)의 보안 설정으로 이동합니다.







이 작업을 완료하면 API 키가 표시됩니다. API 키가 생성되는 즉시 복사하여 쉽게 검색할 수 있는 곳에 저장해야 합니다.

3단계: 동물 컬렉션 만들기



코드 내에서 상호 작용할 컬렉션을 만들어야 합니다.





그런 다음 Save 버튼을 클릭합니다.

4단계: Fauna를 Nodejs에 연결하기



다음으로 Fauna 및 Express용 Nodejs 패키지를 가져와야 합니다. npm에서 사용할 수 있으며 터미널에서 한 줄로 설치할 수 있습니다.

$ npm install --save faunadb express

이것이 설치되면 FaunaJavascript driver docs에서 제공하는 샘플 코드를 실행합니다.

    const express = require('express');
    const faunadb = require('faunadb'),
      q = faunadb.query;

    const client = new faunadb.Client({
      secret: 'YOUR_FAUNADB_SECRET',
    });

    const app = express();
    app.use(express.json())
    const PORT = process.env.PORT || 8000;

    app.get('/', async (req, res) => {
      try {
        const createP = await client.query(
          q.Create(q.Collection('todos'), { data: { testField: 'testValue' } })
        );
        console.log(createP);
      } catch (error) {
        console.log(error);
      }
    });

    app.listen(PORT, () => console.log(`Listening at port ${PORT}`));



이 경로를 테스트하기 위해 모든 HTTP 클라이언트를 사용할 수 있습니다. 저는 Postman(할 수 있는 것download here )을 사용할 것이지만 가장 편한 것을 사용할 수 있습니다(예: cURL, Insomnia, Postwoman 등).

시작 dev 서버에 다음 명령을 사용하는 것을 잊지 마십시오.

node src/index.js

다음에 대한 GET 요청을 만들어 보겠습니다.

http://localhost:8000/

그런 다음 터미널을 확인하면 다음과 같이 표시됩니다.

    {
      ref: Ref(Collection("todos"), "302049452692079110"),
      ts: 1624315655320000,
      data: { testField: 'testValue' }
    }


5단계: 모든 할 일 검색



컬렉션에서 모든 작업을 가져올 수 있는 첫 번째 익스프레스 경로를 만들어 봅시다.

    app.get('/todos', async (req, res) => {
      try {
        let todos = await client.query(
          q.Map(
            q.Paginate(q.Documents(q.Collection("todos"))),
            q.Lambda("X", q.Get(q.Var("X")))
          )
        )

        res.status(200).json(todos)
      } catch (error) {
        res.status(500).json({error: error.description})
      }
    });



6단계: 단일 할 일 검색



이 섹션에서는 컬렉션을 지정하여 컬렉션에서 todo를 검색할 수 있는 익스프레스 경로를 생성합니다id.

    app.get('/todos/:id', async (req, res) => {
      try {
        const {data} = await client.query(
          q.Get(q.Ref(q.Collection('todos'), req.params.id))
        );
        res.status(200).json(data)
      } catch (error) {
        res.status(500).json({error: error.description})
      }
    });



7단계: 할 일 만들기



이 섹션에서는 컬렉션으로 작업을 수행create/add할 수 있는 익스프레스 경로를 만들 것입니다.

    app.post('/todos', async (req, res) => {

      try {
        const {title, description } = req.body;
        const { data } = await client.query(
          q.Create(q.Collection('todos'), { data: { title, description } })
        );

        res.status(201).json(data);
      } catch (error) {
        res.status(500).json({error: error.description})
      }
    });



8단계: 할 일 업데이트



이 섹션에서는 todoid를 지정하여 todo를 업데이트할 수 있는 익스프레스 경로를 생성합니다.

    app.put('/todos/:id', async (req, res) => {

      try {
        const {title, description } = req.body;
        const { data } = await client.query(
          q.Update(q.Ref(q.Collection('todos'), req.params.id), 
          { data: { title, description } },
          )
        );

        res.status(201).json(data);
      } catch (error) {
        res.status(500).json({error: error.description})
      }
    });



7단계: 할 일 삭제



이 섹션에서는 해당 항목id을 지정하여 todo를 삭제할 수 있는 익스프레스 경로를 생성합니다.

   app.delete('/todos/:id', async (req, res) => {

      try {
        const { data } = await client.query(
          q.Delete(q.Ref(q.Collection('todos'),  req.params.id))
        );

        res.status(204).json(data);
      } catch (error) {
        res.status(500).json({error: error.description})
      }
    });


다음으로 이전에 언급한 Postman을 사용하여 코드를 테스트할 것입니다.

모든 할 일을 가져오기 위해 GET 요청을 만들어 보겠습니다.

http://localhost:8000/todos


GET가 할 일을 가져오기 위해 id 요청을 만들어 이것을 시도해 봅시다.

http://localhost:8000/todos/302052755930874368


POST todo에 add/create 요청을 만들어 이것을 시도해 봅시다:

http://localhost:8000/todos/302052755930874368



todo를 업데이트하기 위해 PUT 요청을 만들어 이것을 시도해 봅시다.

http://localhost:8000/todos/302052755930874368



todo를 제거하기 위해 DELETE 요청을 만들어 이것을 시도해 봅시다:

http://localhost:8000/todos/302052755930874368



결론



이 기사에서는 ExpressJs를 사용하여 Fauna 및 Nodejs로 작업CRUD을 수행하는 방법을 배웠습니다.
데모 애플리케이션의 소스 코드는 GitHub에서 사용할 수 있습니다.

궁금한 점이 있으면 주저하지 말고 Twitter에서 저에게 연락하십시오.

좋은 웹페이지 즐겨찾기