const nodemailer = require("nodemailer"); router.sendMail = (req, res) => { const stmpconfig = { host: "smtpAddress", port: "465", secure: true, auth: { user: "abc@def.com", pass: "123456" } }; const from = "발신자명 < abc@def.com >"; const to = "수신자 이메일 주소"; const subject = "제목"; const html = "<p>내용</p>"; let mailOptions = { from, to, subject, html }; const transporter = nodemailer.createTransport(stmpconfig); transporter.verify((err, success) => { if (err) console.error(err); console.log("Your config is correct / " + success); }); transporter.sendMail(mailOptions, function(err, res) { if (err) { console.error("🤕 NodeMailer test failed with error:\n", err); } else { console.log("this is a new password: " + password); console.log("📬 Successfully sent NodeMailer test with result:\n", res); } }); transporter.close; res.send("it's over"); };


router.updateQA = (req, res) => {
    const data = (req.method == 'POST') ? req.body : req.query;
    const id = req.query._id;
    const fields = 'name, profile.qa'
    UserData.model
        .findById(id)
        .exec((err, user) => {
            if (err) return res.apiError(err);
            if (!user) return res.apiResponse({ message: "no user" });
            user.getUpdateHandler(req).process(
                data,
                { 
                    flashErrors: true, 
                    fields: fields,
                    errorMessage: 'error!!'
                },
                err => {
                    if (err) return res.apiError("error", err);
                    res.apiResponse({
                        status: "success",
                        result: user
                    });
                }
            );
        })
}

https://keystonejs.com/api/list/update-item/

fields: String|Array

A list of fields to attempt to update. All other fields will not be updated even if values are provided. 
If a string is passed, it will attempt to use list-to-array to transform the string.

즉 fields 에 주어진 필드들 외에 필드들은 값이 주어지더라도 업데이트 안함. 그리고 주어진 필드중의 필드를 업데이트 하지 않아도 상관없음.
그러나 업데이트 할 Document 의 필드 속성중 Relationship Type 필드들은 업데이트시 값을 주지 않으면 값이 날라감. 그외 필드들은 영향 없음
그래서 RelationshipType이 들어가는 Document 업데이트는 무조건 사용해야할듯



Ex)
-User Model

User.add({
    ... ,
	password: { type: Types.Password, initial: true, required: true },
	name: { type: Types.Name },
	birthday: { type: Types.Date, index: true, default: Date.now },
	gender: { type: Types.Select, options: 'M, W', default: 'M' },
	nationality: { type: Types.Relationship, ref: 'Nationality', initial: true },
    ...
})

let fields = 'password, name, gender, birthday';
if (data.nationality) fields += ', nationality';

password, name, gender, birthday 필드들은 relationship 타입이 아니라 값을 넣어도 되고 안넣어도 됨.
하지만 relationship 타입인 nationality 가 fields 에 들어있고 api 날릴때 key, value 값이 주어지지 않으면 null 값이 들어가 원래 값이 날라감.
그래서 User update 할 때 data 에 nationality 키가 포함 되어있으면 fields 에 포함시키고 아니면 포함 안 시킴.


'IT > KeystonJS' 카테고리의 다른 글

nodemailer 로 메일 보내기 + Keystonejs  (0) 2018.12.28
Keystone + Next js Routing 설정  (0) 2018.12.10
Keystonejs + Nextjs Production mode 설정  (0) 2018.12.05

Keystone 이 Routing 하지 않고 Next가 하게 하려면

1.

kestone.js 를


require('dotenv').config();

const next = require('next');
const dev = process.env.NODE_ENV !== 'production';
const app = next({ dev });


var keystone = require('keystone');

keystone.init({
    'name': 'keystone_next_react',
    'brand': 'keystone_next_react',
    'auto update': true,
    'session': true,
    'auth': true,
    'user model': 'User',
});


keystone.import('models');

app.prepare()
    .then(() => {
        keystone.set('locals', {
            _: require('lodash'),
            env: keystone.get('env'),
            utils: keystone.utils,
            editable: keystone.content.editable,
        });
        
        keystone.set('routes', require('./routes')(app));
        
        keystone.set('nav', {
            posts: ['posts', 'post-categories'],
            users: 'users',
        });
        
        keystone.start();
    })


이렇게 바꾼다.


keystone.set('routes', require('./routes')(app));


이부분이 keytone의 라우팅을 next가 하게 해주는 부분이다.


next가 라우팅을 하게 하려면

프로젝트의 root 에서 pages 폴더를 만들어 그 안에 보여줄 화면들을 만든다. 

먼저 해당 글은 Keystonejs로 deploy를 한다는 베이스 하에 진행 됩니다.


Nextjs deploy 방법은 


https://nextjs.org/docs/#production-deployment 참고하세요.


Keystonejs deploy 방법은 .env 파일에 NODE_ENV=production 를 추가하고


keystone.js 파일에서


// Simulate config options from your production environment by
// customising the .env file in your project's root folder.
require("dotenv").config();

const next = require("next");
const dev = process.env.NODE_ENV !== "production";
const app = next({ dev });

// Require keystone
var keystone = require("keystone");

// Initialise Keystone with your project's configuration.
// See http://keystonejs.com/guide/config for available options
// and documentation.

keystone.init({
    name: "NextExample",
    brand: "NextExample",
    favicon: "public/favicon.ico",
    "auto update": true,
    session: true,
    auth: true,
    "user model": "User"
});

// Load your project's Models
keystone.import("models");

// Start Next app
app.prepare().then(() => {
    // Load your project's Routes
    keystone.set("routes", require("./routes")(app));

    // Configure the navigation bar in Keystone's Admin UI
    keystone.set("nav", {
        posts: ["posts", "post-categories"],
        users: "users"
    });

    keystone.start();
});


const dev = process.env.NODE_ENV !== "production";



const dev = process.env.NODE_ENV === "production";


로 바꾸고 터미널에서

node keystone 으로 실행하면 끝....


헤맸던 이유

 - Keystone 과 Next 둘 중 베이스를 정한 뒤, 어떤걸 build 시키고 어떤걸 deploy 시키는지에 관해 개념이 모호하였음.

 - .env 에서 NODE_ENV=production 을 작성만 하면 되는지 알고 작성 뒤 실행시키니 


터미널에


throw new Error("Could not find a valid build in the '".concat(this.distDir, "' directory! Try building your app with 'next build' before starting the server."));

        ^


Error: Could not find a valid build in the '/home/pc/Documents/Projects/nextexample/.next' directory! Try building your app with 'next build' before starting the server.


가 나와서 나도 모르게 당연히, next build 를 먼저 하고 해야한다고 생각해버림.....


오늘 또 한삽 거하게 펐다... 

+ Recent posts