miragejs - fake server for nextjs

수박·2022년 1월 26일
0

Next

목록 보기
2/3
post-custom-banner

mirage js


fake server 라이브러리

install

npm i mirage

example code for app

베이스서버 세팅

/// server.js
import { createServer, Model } from "miragejs";

export function makeServer({ environment = "test" } = {}) {
  let server = createServer({
    environment,

    models: {
      movie: Model,
    },

    seeds(server) {
      server.create("movie", { name: "Inception", year: 2010 });
      server.create("movie", { name: "Interstellar", year: 2014 });
      server.create("movie", { name: "Dunkirk", year: 2017 });
    },

    routes() {
      this.namespace = "api";
      this.get("/movies", (schema) => {
        return schema.movies.all();
      });
      this.namespace = "";
      this.passthrough();
    },
  });

  return server;
}
//_app.tsx
import { makeServer } from "mirage/server";

function MyApp({ Component, pageProps }: AppProps) {
  if (process.env.NODE_ENV === "development") {
    makeServer({ environment: "development" });
  }
...

page단위

  let [movies, setMovies] = useState([]);

  const getData = async () => {
    const res = await fakeRequestMethod.get({ endPoint: "/api/movies" });
    console.log(res.data.movies);
    setMovies(res.data.movies);
  };
  useEffect(() => {
    getData();
  }, []);
  return (
    <MainWrapper>
      <NavBar />
      <section>
        Confirm
        <ul>
          {movies.map((movie) => (
            <li key={movie.id}>
              {movie.name} ({movie.year})
            </li>
          ))}
        </ul>
      </section>
    </MainWrapper>
  );

돈 내고 쓰는 Postman이 최고시다

post-custom-banner

0개의 댓글