前言:昨天大致上對於甚麼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
開啟瀏覽器
MongoDB
apollographql
六角Ray助教教學文