iT邦幫忙

2024 iThome 鐵人賽

DAY 12
0
佛心分享-SideProject30

用 Next.js 實作屋況查詢評估專家網站系列 第 12

[Day 12] 後端環境建置-我的第一支API

  • 分享至 

  • xImage
  •  

前言:昨天大致上對於甚麼GrahpQL,以及預計會用甚麼套件去建置一個API Service,了解基本用法,如何去將資料建立可CRUD(新增(Create)、查詢(Read)、修改(Update)、刪除(Delete))的API Function

今天會利用Node.js這個程式語言分享如何建置我第一支API,以使用者功能登入/註冊為例:

1.import 模組

  const { ApolloServer, gql } = require("apollo-server");

2.定義好資料的結構


const UserModel = mongoose.model("Users", {
  username: String,
  password: String,
});

3.定義程式碼結構

const resolvers = {
    Query: {
       ...
    },
    Mutation: {
        register: async (parent, { username, password }) => {
          const passwordRegex = /^[A-Z].{5,}$/;
          if (!passwordRegex.test(password)) {
            throw new AuthenticationError(
              "Password must start with an uppercase letter and be at least 6 characters long"
            );
          }

          const existingUser = await UserModel.findOne({ username });
          if (existingUser) {
            throw new AuthenticationError("User already exists");
          }

          const hashedPassword = await bcrypt.hash(password, 10);

          const newUser = new UserModel({ username, password: hashedPassword });
          await newUser.save();

          const token = jwt.sign(
            { id: newUser.id, username: newUser.username },
            "your-secret-key",
            {
              expiresIn: "1d",
            }
          );

          return { token, user: { id: newUser.id, username: newUser.username } };
        },
    }
}
const server = new ApolloServer({
  typeDefs,
  resolvers,

  persistedQueries: false,
  playground: true,
});

server.listen({ port: process.env.PORT || 4000 }).then(({ url }) => {
  console.log(`Server is ${url}`);
});


這樣就撰寫好你的第一支API程式囉
接下來執行以下node指令即可在您本機開啟本地伺服器環境!

   npm start

預設會以http:localhost:4000開啟瀏覽器

https://ithelp.ithome.com.tw/upload/images/20240812/20132295LQGtp3aaG5.png

https://ithelp.ithome.com.tw/upload/images/20240812/20132295A1DstDmdTq.png


參考資源

MongoDB
apollographql
六角Ray助教教學文


上一篇
[Day 11] 後端環境建置-Apollo GraphQL Server
下一篇
[Day 13] 後端環境建置-測試API
系列文
用 Next.js 實作屋況查詢評估專家網站24
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言