인스타그램 클론코딩 7일차 - BE

박병준·2021년 7월 28일
0
post-thumbnail

#3.6 Comments

find할 때 select를 총해 원하는 데이터만을 가져올 수 있다. include는 이와 반대로 모든 데이터를 가져온다.

select와 include는 같이 쓸 수 없다.

// createComment.resolvers.js
const resolverFn = async (_, { photoId, payload }, { loggedInUser }) => {
    const photo = await client.photo.findUnique({
        where: {
            id: photoId
        },
        select: {// photo의 id만 가져와서 확인한다.
            id: true,
        }
    });
    if (!photo) {
        return {
            ok: false,
            error: "Photo not found"
        };
    }
    await client.comment.create({
        data: {
            photo: {
                connect: {
                    id: photoId,
                }
            },
            user: {
                connect: {
                    id: loggedInUser.id,
                }
            },
            payload,
        }
    });
    return {
        ok: true,
    };
};

#3.7 protectedResolver Refactor

resolver가 받는 4개 인자중 마지막인 info는 query나 mutation과 관련된 많은 정보를 담고있다.

// users.utils.js
export const protectedResolver = (ourResolver) => (root, args, context, info) => {
    if (!context.loggedInUser) {
        const query = info.operation.operation === "query";
        if (query) {
            return null;
        } else {
            return {
                ok: false,
                error: "Please log in to perform this action"
            };
        }
    }
    return ourResolver(root, args, context, info);
};

#3.8 AWS S3

aws에 data를 업로드하는 방법

  1. npm i aws-sdk

  2. aws에 로그인 한다.

  3. 오른쪽위의 리젼을 서울로 설정한다.

  4. aws의 서비스에서 IAM을 찾아 들어간다.
    업로드할 수 있는 API key를 만들기 위해서이다.

  5. 사용자 클릭 후 사용자를 추가한다.
    -프로그래밍 방식 액세스: 프로그램이 이 유저를 사용한다.
    -AWS Management Console 액세스: 다른 동료들이 이 계정에 로그인해서 접근하게 만든다.

  6. 다음으로 넘어가 권한설정에서 기존 정책 연결에서 AmazonS3FullAccess를 찾아 체크해준다.
    -S3: Simple Storage Service

  7. 태그와 검토를 넘긴다.

  8. 액세스 키와 비밀 엑세스 키가 보일텐데 비밀 엑세스 키는 이 때 한번만 보여주게 된다. 따라서 다른 곳에 잘 적어두고 다른사람에게는 절대 보여주면 안된다.

  9. 작업 폴더로 들어와 .env에 적어두고 aws로 돌아가 S3를 연다.

  10. 버킷을 만든다.

  11. 작업 폴더로 돌아와 aws를 설정해준다.

// shared.utils.js
import AWS from "aws-sdk";

AWS.config.update({
    credentials: {
        accessKeyId: process.env.AWS_KEY,
        secretAccessKey: process.env.AWS_SECRET,
    },
});

#3.9 Upload

// shared.utils.js
import AWS from "aws-sdk";

AWS.config.update({//설정
    credentials: {
        accessKeyId: process.env.AWS_KEY,
        secretAccessKey: process.env.AWS_SECRET,
    },
    region: "ap-northeast-2",
});

const Bucket = "instaclone-upload-aws";
const s3 = new AWS.S3();

export const uploadToS3 = async (file, userId, folderName) => {
    const { filename, createReadStream } = await file;
    const newFilename = `${folderName}/${userId}-${Date.now()}-${filename}`;
    const readStream = createReadStream();
    const { Location } = await s3.upload({
        Bucket,
        Key: newFilename,
        ACL: "public-read",
        Body: readStream
    }).promise();

    return Location;
};
profile
뿌셔뿌셔

0개의 댓글